def app(user, plan_record): app = create_app( { "TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:", "SQLALCHEMY_TRACK_MODIFICATIONS": False, "SECRET_KEY": b"my_secret_key", } ) with app.app_context(): db.create_all() admin_role = Role(name="admin") user_role = Role(name="user") db.session.add(admin_role) db.session.add(user_role) user.roles = [admin_role, user_role] db.session.add(user) place = Place(name="Lowell, MA", description="A town") db.session.add(place) plan = PlanSchema().load(plan_record) plan.user = user db.session.add(plan) db.session.commit() return app
def app(user, plan_record): app = create_app(test_config) with app.app_context(): db.create_all() admin_role = Role(name="admin") user_role = Role(name="user") db.session.add(admin_role) db.session.add(user_role) # Admin user user.roles = [admin_role, user_role] db.session.add(user) # Non-admin user non_admin = User(first="Example", last="Person", email="*****@*****.**") non_admin.roles = [user_role] db.session.add(non_admin) place = Place(name="Lowell, MA", description="A town") db.session.add(place) plan = PlanSchema().load(plan_record) plan.user = user db.session.add(plan) db.session.commit() return app
def new_roles(app): roles = [ Role(title='Operations Intern'), Role(title='Operations Coordinator'), Role(title='Operations Assistant'), Role(title='Operations Manager'), ] return roles
def setUp(self): """ Set up test application. """ self.app = create_app('testing') self.client = self.app.test_client() self.client.headers = {'Authorization': getenv('TEST_TOKEN')} self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() self.board1 = Board() self.board2 = Board() self.conversation1 = Conversation() self.conversation2 = Conversation() self.deposit1 = Deposit() self.deposit2 = Deposit() self.estate1 = Estate(address="Random Address 1") self.estate2 = Estate(address="Random Address 2") self.estate3 = Estate() self.headers = {'Authorization': getenv('TEST_TOKEN')} self.message1 = Message(sender=1, content='Random Content') self.message2 = Message(sender=2, content='Random Content') self.message3 = Message() self.payment1 = Payment() self.payment2 = Payment() self.role1 = Role(title='basic') self.role2 = Role(title='admin') self.role3 = Role(title='super_admin') self.role4 = Role() self.unit1 = Unit(name="Random Unit 1") self.unit2 = Unit(name="Random Unit 2") self.unit3 = Unit() self.user1 = User(name="First1 Middle1 Last1", phone_number="000 12 3456781", email="*****@*****.**", password=digest('ABC123!@#')) self.user2 = User(name="First2 Middle2 Last2", phone_number="000 12 3456782", email="*****@*****.**", password=digest('ABC123!@#')) self.user3 = User() self.user_new_data1 = {'phone_number': "000 12 3456783"} self.user_new_data2 = {'bad_field': "random"} self.wallet1 = Wallet() self.wallet2 = Wallet() self.user1_dict = { "name": "First1 Middle1 Last1", "phone_number": "000 12 3456781", "email": "*****@*****.**", "password": "******" } self.conversation3_dict = {"participants": [1, 2]} self.message4_dict = {"content": "New Message."} self.board3_dict = {'members': [1, 2]}
def app(user, plan_record): app = create_app(test_config) with app.app_context(): db.create_all() admin_role = Role(name="admin") user_role = Role(name="user") db.session.add(admin_role) db.session.add(user_role) # Admin user user.roles = [admin_role, user_role] db.session.add(user) # Non-admin user non_admin = User(first="Example", last="Person", email="*****@*****.**") non_admin.roles = [user_role] db.session.add(non_admin) place = Place( slug="lowell", name="Lowell, MA", state="Massachusetts", description="A town", districting_problems=[ DistrictingProblem( number_of_parts=9, name="Town Council", plural_noun="Town Council Districts", ) ], units=[ UnitSet( name="Blocks", unit_type="block", slug="blocks", bounds="[[0, 100], [0, 100]]", ) ], ) db.session.add(place) plan = Plan(**PlanSchema().load(plan_record)) plan.user = user db.session.add(plan) db.session.commit() return app
def setUpClass(cls): DBModel.metadata.drop_all(sqla_engine) DBModel.metadata.create_all(sqla_engine) r1, r2 = Role(name='admin'), Role(name='pikus') DBSession.add(r1) DBSession.add(r2) a = Account(username='******', fullName='Greg Burek', email='*****@*****.**') a.set_password('dupa') a.roles.extend((r1, r2)) DBSession.add(a) DBSession.commit() cls.DBSession = DBSession
def centre_societies_roles_data_dev(production=False): """Generate center societies and role data.""" # test centers nairobi = Center(name='nairobi') kampala = Center(name='kampala') lagos = Center(name='lagos') # societies phoenix = Society(name="phoenix") istelle = Society(name="istelle") sparks = Society(name="sparks") invictus = Society(name="invictus") # roles available roles = (Role(uuid="-KXGy1EB1oimjQgFim6F", name="success"), Role(uuid="-KXGy1EB1oimjQgFim6L", name="finance"), Role(uuid="-KXGy1EB1oimjQgFim6C", name="fellow"), Role(uuid="-KkLwgbeJUO0dQKsEk1i", name="success ops"), Role(uuid="-KiihfZoseQeqC6bWTau", name="andelan"), Role(name="society president"), Role(name="society vice president"), Role(name="society secretary")) return (roles, nairobi, kampala, lagos, phoenix, istelle, sparks, invictus) if not production else (roles, phoenix, istelle, sparks, invictus)
async def test_role_update(app: AsyncClient, db, user, token, manage_roles_role, request_data, new_data, status): try: query = """ INSERT INTO roles (id, name, color, permissions, position) VALUES (create_snowflake(), 'test update', 0, 0, (SELECT COUNT(*) FROM roles) + 1) RETURNING *; """ role = Role(**await Role.pool.fetchrow(query)) await UserRole.create(user.id, manage_roles_role.id) res = await app.patch( f"/api/v1/roles/{role.id}", json=request_data, headers={"Authorization": token}, ) assert res.status_code == status role = await Role.fetch(role.id) data = role.as_dict() data.pop("id") data.pop("position") assert data == new_data finally: await db.execute( "DELETE FROM userroles WHERE role_id = $1 AND user_id = $2;", manage_roles_role.id, user.id, ) await db.execute("DELETE FROM roles WHERE id = $1", role.id)
async def manage_roles_role(db): query = """ INSERT INTO roles (id, name, color, permissions, position) VALUES (create_snowflake(), $1, $2, $3, (SELECT COUNT(*) FROM roles) + 1) RETURNING *; """ record = await Role.pool.fetchrow(query, "Roles Manager", 0x0, ManageRoles().value) yield Role(**record) await db.execute("DELETE FROM roles WHERE id = $1;", record["id"])
def seed_roles(): """ Add initial roles to the database. """ Role.drop() roles = ['basic', 'admin', 'super_admin'] for role in roles: new_role = Role(title=role) new_role.save() print('\nRoles Seeded.\n')
def seed_roles(): """ Seeds sample roles """ titles = [ 'Operations Intern', 'Operations Coordinator', 'Operations Assistant', 'Operations Manager', ] for title in titles: db.session.add(Role(title=title)) db.session.commit()
def handle(self, *args, **options): try: role_names = [settings.ROLE_PROJECT_ADMIN, settings.ROLE_ANNOTATOR, settings.ROLE_ANNOTATION_APPROVER] except KeyError as key_error: self.stderr.write(self.style.ERROR(f'Missing Key: "{key_error}"')) for role_name in role_names: if Role.objects.filter(name=role_name).exists(): continue role = Role() role.name = role_name try: role.save() except DatabaseError as db_error: self.stderr.write(self.style.ERROR(f'Database Error: "{db_error}"')) else: self.stdout.write(self.style.SUCCESS(f'Role created successfully "{role_name}"'))
async def test_update_role_positions_down(app: AsyncClient, db, user, token, manage_roles_role): try: roles = [] # manage roles -> 1 -> 3 -> 2 -> 4 role_names = ["1", "3", "2", "4"] for role_name in role_names: query = """ INSERT INTO roles (id, name, color, permissions, position) VALUES (create_snowflake(), $1, 0, 0, (SELECT COUNT(*) FROM roles) + 1) RETURNING *; """ role = Role(**await Role.pool.fetchrow(query, role_name)) roles.append(role) await UserRole.create(user.id, manage_roles_role.id) res = await app.patch( f"/api/v1/roles/{roles[1].id}", json={"position": 4}, headers={"Authorization": token}, ) assert res.status_code == 204 res = await app.get("/api/v1/roles") new_roles = sorted(res.json(), key=lambda x: x["position"]) for i, role in enumerate(new_roles, 1): assert (role["position"] == i ) # make sure roles are ordered with no missing positions for i in range(1, 5): assert new_roles[i]["name"] == str(i) finally: await db.execute( "DELETE FROM userroles WHERE role_id = $1 AND user_id = $2;", manage_roles_role.id, user.id, ) for role in roles: await db.execute("DELETE FROM roles WHERE id = $1", role.id)
async def inner(user=authorization()): query = """ SELECT * FROM roles r WHERE r.id IN ( SELECT ur.role_id FROM userroles ur WHERE ur.user_id = $1 ) """ records = await Role.pool.fetch(query, user.id) if not records: raise HTTPException(403, "Missing Permissions") user_permissions = 0 for record in records: user_permissions |= record["permissions"] if not utils.has_permissions(user_permissions, permissions): raise HTTPException(403, "Missing Permissions") return [Role(**record) for record in records]
async def test_role_add(app: AsyncClient, db, user, token, manage_roles_role): try: query = """ INSERT INTO roles (id, name, color, permissions, position) VALUES (create_snowflake(), 'test add', 0, 0, (SELECT COUNT(*) FROM roles) + 1) RETURNING *; """ role = Role(**await Role.pool.fetchrow(query)) await UserRole.create(user.id, manage_roles_role.id) res = await app.put( f"/api/v1/roles/{role.id}/members/{user.id}", headers={"Authorization": token}, ) assert res.status_code == 204 finally: await db.execute( "DELETE FROM userroles WHERE role_id = $1 AND user_id = $2;", manage_roles_role.id, user.id, ) await db.execute("DELETE FROM roles WHERE id = $1", role.id)
def new_role(app): role = Role(title='Operations Intern') return role
def setUp(self): """Configure test enviroment.""" os.environ['APP_SETTINGS'] = 'Testing' self.patcher = mock.patch( 'api.services.auth.helpers.add_extra_user_info', return_value=(None, None, None)) self.patcher.start() self.app = create_app("Testing") self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() # test client self.client = self.app.test_client() token_payloads_list = [ self.incomplete_payload, self.expired_payload, self.test_cio_role_payload, self.test_society_president_role_payload, self.test_auth_role_payload, self.test_finance_payload, self.test_successops_payload ] for token_payload in token_payloads_list: token_payload.update({ 'iss': self.app.config['API_ISSUER'], 'aud': self.app.config['API_AUDIENCE'] }) self.header = { "Authorization": self.generate_token(self.test_user_payload), "Content-Type": "application/json" } self.success_ops = { "Authorization": self.generate_token(self.test_successops_payload), "Content-Type": "application/json" } self.society_president = { "Authorization": self.generate_token(self.test_society_president_role_payload), "Content-Type": "application/json" } self.sparks_society_president = { "Authorization": self.generate_token(self.test_sparks_society_president_payload), "Content-Type": "application/json" } self.society_secretary = { "Authorization": self.generate_token(self.test_society_secretary_payload), "Content-Type": "application/json" } self.cio = { "Authorization": self.generate_token(self.test_cio_role_payload), "Content-Type": "application/json" } self.finance = { "Authorization": self.generate_token(self.test_finance_payload), "Content-Type": "application/json" } self.bad_token_header = { "Authorization": self.generate_token({"I don't know": "what to put here"}), "Content-Type": "application/json" } # test centers self.nairobi = Center(name='Nairobi') self.kampala = Center(name='Kampala') self.lagos = Center(name='Lagos') # test societies self.phoenix = Society(name="Phoenix", color_scheme="#00001", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.istelle = Society(name="iStelle", color_scheme="#00002", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.sparks = Society(name="Sparks", color_scheme="#00003", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.invictus = Society(name="Invictus", color_scheme="#00004", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") # test roles self.successops_role = Role(uuid="-KkLwgbeJUO0dQKsEk1i", name="success ops") self.fellow_role = Role(uuid="-KXGy1EB1oimjQgFim6C", name="Fellow") self.success_role = Role(uuid="-KXGy1EB1oimjQgFim6F", name="success ops") self.finance_role = Role(uuid="-KXGy1EB1oimjQgFim6L", name="finance") self.lf_role = Role(uuid="d47ec8a7-3f09-44a5-8188-ff1d40ef35b6", name="Learning Facilitator") self.president_role = Role(uuid="-KXGyd2udi2", name="society president") self.v_president_role = Role(uuid="-KXGy32odnd", name="vice president") self.secretary_role = Role(uuid="-KXGy12odfn2idn", name="society secretary") self.cio_role = Role(uuid="-KXGionceu24i2y", name="cio") # test cohorts self.cohort_12_Ke = Cohort(name="cohort-12", center=self.nairobi) self.cohort_14_Ke = Cohort(name="cohort-14", center=self.nairobi) self.cohort_12_Ug = Cohort(name="cohort-12", center=self.kampala) self.cohort_1_Nig = Cohort(name="cohort-1", center=self.lagos) # test users self.test_user = User(uuid="-KdQsMt2U0ixIy_-yWTSZ", name="Test User", photo="https://www.link.com", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.test_user_2 = User(uuid="-KdQsawesome_usedk2cckjfbi", name="Test User2", photo="https://www.link.com", email="*****@*****.**", center=self.kampala, cohort=self.cohort_12_Ug, society=self.sparks) self.test_user_3 = User(uuid="-KdQsawesomb2dunkdnw", name="Test User3", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.invictus) self.test_cio = User( uuid="-KdQdsdadqwdqomb2dunkdnw", name="Test CIO", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, ) self.test_cio.roles.append(self.cio_role) self.president = User( uuid="-KdQsMtixG4U0y_-yJEH", name="Test President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.president.roles.append(self.president_role) self.vice_president = User( uuid="-KdQsMtixGc2nuekwnd", name="Test Vice-President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.sparks) self.vice_president.roles.append(self.v_president_role) self.secretary = User( uuid="-Kuty7hryt8cbkc", name="Test Secretary", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_14_Ke, society=self.invictus) self.secretary.roles.append(self.secretary_role) # test ActivityType self.hackathon = ActivityType(name="Hackathon", description="A Hackathon", value=100) self.tech_event = ActivityType(name="Tech Event", description="Organize a tech event", value=2500) self.interview = ActivityType( name="Bootcamp Interviews", description="Interviewing candidate for a fellow" " recruiting event", value=20, supports_multiple_participants=True) # test Activity self.alibaba_ai_challenge = Activity( name='Fashion challenge', activity_type=self.hackathon, activity_date=datetime.date.today() + datetime.timedelta(days=21), added_by=self.president) self.js_meet_up = Activity(name='Nairobi Js meetup', activity_type=self.tech_event, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) self.bootcamp_xiv = Activity(name='Bootcamp XIV Interviews - Nairobi', activity_type=self.interview, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) # test LoggedActivity self.log_alibaba_challenge = LoggedActivity( name="my logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.invictus, activity_type=self.hackathon) self.log_alibaba_challenge2 = LoggedActivity( name="my second logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.sparks, activity_type=self.hackathon) self.redemp_req = RedemptionRequest(name="T-shirt Funds Request", value=2500, user=self.test_user, center=self.test_user.center, society=self.test_user.society) # save common items to db self.tech_event.save() self.interview.save() self.hackathon.save() self.test_user.save()
def seed_test_data(): """ Seed data to be used for testing. """ db.drop_all() db.create_all() payment_1 = Payment() payment_2 = Payment() payment_3 = Payment() payment_4 = Payment() payment_1.insert('deposits', [Deposit( amount=1000.0), Deposit(amount=500.0)]) payment_2.insert('deposits', [Deposit( amount=1000.0), Deposit(amount=500.0)]) payment_3.insert('deposits', [Deposit(amount=1000.0)]) payment_4.insert('deposits', [Deposit(amount=1000.0)]) wallet_1 = Wallet() wallet_2 = Wallet() wallet_3 = Wallet() wallet_4 = Wallet() wallet_1.insert('payments', [payment_1, payment_2]) wallet_2.insert('payments', [payment_3]) wallet_3.insert('payments', [payment_4]) estate1 = Estate(address='Casterly Rock') estate2 = Estate(address='Dorne') estate3 = Estate(address='Dragonstone') estate2.insert('payment', wallet_2.payments[0]) estate3.insert('payment', wallet_3.payments[0]) unit1 = Unit(name='No. 1') unit2 = Unit(name='No. 2') unit3 = Unit(name='No. 1') unit4 = Unit(name='No. 2') unit5 = Unit(name='No. 3') unit1.insert('payment', wallet_1.payments[0]) unit2.insert('payment', wallet_1.payments[1]) estate1.insert('estate_units', [unit1, unit2]) estate2.insert('estate_units', [unit3]) estate3.insert('estate_units', [unit4, unit5]) board1 = Board() board2 = Board() board1.insert('estates_owned', [estate1, estate2]) board2.insert('estates_owned', [estate3]) board1.insert('units_owned', [unit5]) user0 = User( name="Test User", phone_number="000 00 0000000", email="*****@*****.**", password=digest('ABC123!@#1')) user1 = User( name="Jaime Lannister", phone_number="000 12 3456781", email="*****@*****.**", password=digest('ABC123!@#1')) user2 = User( name="Oberyn Martell", phone_number="000 12 3456782", email="*****@*****.**", password=digest('ABC123!@#2')) user3 = User( name="Daenerys Targaryen", phone_number="000 12 3456783", email="*****@*****.**", password=digest('ABC123!@#3')) conversation1 = Conversation() conversation2 = Conversation() message1 = Message(sender=user1.name, content='Content 1') message2 = Message(sender=user2.name, content='Content 2') message3 = Message(sender=user3.name, content='Content 3') conversation1.insert('messages', [message1, message2]) conversation2.insert('messages', [message3]) user0.insert('boards', [board1]) user1.insert('boards', [board1]) user2.insert('boards', [board1]) user3.insert('boards', [board2]) user1.insert('units', [unit1, unit2]) user2.insert('units', [unit3]) user3.insert('units', [unit4]) user0.insert('wallet', wallet_4) user1.insert('wallet', wallet_1) user2.insert('wallet', wallet_2) user3.insert('wallet', wallet_3) user1.insert('conversations', [conversation1, conversation2]) user2.insert('conversations', [conversation1, conversation2]) user3.insert('conversations', [conversation1]) role1 = Role(title='admin') role2 = Role(title='basic') role3 = Role(title='super_admin') role3.insert('users', [user0, user1]) role2.insert('users', [user0, user1, user2, user3]) role1.insert('users', [user0, user3]) role1.save() role2.save() role3.save() print('\nTest Data Seeded.\n')