def test_list_submission_users_cgac_frec_affil(database): """ Test listing users based on both cgac and frec affiliations """ cgacs = [CGACFactory(cgac_code='000'), CGACFactory(cgac_code='111')] frecs = [FRECFactory(frec_code='0000', cgac=cgacs[0]), FRECFactory(frec_code='1111', cgac=cgacs[1])] first_user = UserFactory.with_cgacs(cgacs[0], name='Test User 1', email='*****@*****.**') other_user = UserFactory.with_cgacs(cgacs[1], name='Test User', email='*****@*****.**') third_user = UserFactory.with_cgacs(cgacs[1], name='Frec User', email='*****@*****.**') third_user.affiliations =\ third_user.affiliations + [UserAffiliation(frec=frecs[0], user_id=third_user.user_id, permission_type_id=PERMISSION_TYPE_DICT['reader'])] database.session.add_all(cgacs + frecs + [first_user, other_user]) database.session.commit() # Third user now has cgac 111 and frec 0000 sub_1 = SubmissionFactory(frec_code=frecs[0].frec_code, user_id=first_user.user_id, is_fabs=False) sub_2 = SubmissionFactory(cgac_code=cgacs[1].cgac_code, user_id=other_user.user_id, is_fabs=False) sub_3 = SubmissionFactory(frec_code=frecs[1].frec_code, user_id=other_user.user_id, is_fabs=False) database.session.add_all([sub_1, sub_2, sub_3]) database.session.commit() g.user = third_user response = list_submission_users(False) user_response = json.loads(response.data.decode('UTF-8'))['users'] # List both other users because one has a frec agency and one has a cgac assert len(user_response) == 2 assert {user_response[0]['user_id'], user_response[1]['user_id']} == {first_user.user_id, other_user.user_id} assert {user_response[0]['name'], user_response[1]['name']} == {first_user.name, other_user.name} assert {user_response[0]['email'], user_response[1]['email']} == {first_user.email, other_user.email}
def test_list_submission_users_frec_affil(database): """ Test listing users based on frec affiliations """ cgacs = [CGACFactory(cgac_code='000'), CGACFactory(cgac_code='111')] frecs = [FRECFactory(frec_code='0000', cgac=cgacs[0]), FRECFactory(frec_code='1111', cgac=cgacs[1])] first_user = UserFactory.with_cgacs(cgacs[0], name='Test User 1', email='*****@*****.**') other_user = UserFactory.with_cgacs(cgacs[1], name='Test User', email='*****@*****.**') third_user = UserFactory(name='Frec User', email='*****@*****.**') third_user.affiliations = [UserAffiliation(frec=frecs[0], user_id=third_user.user_id, permission_type_id=PERMISSION_TYPE_DICT['reader'])] database.session.add_all(cgacs + frecs + [first_user, other_user]) database.session.commit() sub_1 = SubmissionFactory(frec_code=frecs[0].frec_code, user_id=first_user.user_id, is_fabs=False) sub_2 = SubmissionFactory(cgac_code=cgacs[1].cgac_code, user_id=other_user.user_id, is_fabs=False) sub_3 = SubmissionFactory(frec_code=frecs[1].frec_code, user_id=other_user.user_id, is_fabs=False) database.session.add_all([sub_1, sub_2, sub_3]) database.session.commit() g.user = third_user response = list_submission_users(False) user_response = json.loads(response.data.decode('UTF-8'))['users'] # List the first user because they have a submission with that frec assert len(user_response) == 1 assert user_response[0]['user_id'] == first_user.user_id assert user_response[0]['name'] == first_user.name assert user_response[0]['email'] == first_user.email
def test_permissions_filter_agency_user(database, monkeypatch): sess = database.session # Setup agencies db_objects = [] cgac1 = CGACFactory(cgac_code='089', agency_name='CGAC') cgac2 = CGACFactory(cgac_code='011', agency_name='CGAC Associated with FREC') cgac3 = CGACFactory(cgac_code='091', agency_name='Other CGAC Associated with FREC') frec1 = FRECFactory(cgac=cgac2, frec_code='1125', agency_name='FREC 1') frec2 = FRECFactory(cgac=cgac3, frec_code='0923', agency_name='FREC 2') db_objects.extend([cgac1, cgac2, cgac3, frec1, frec2]) # Setup submissions sub1 = SubmissionFactory(cgac_code=cgac1.cgac_code, frec_code=None) sub2 = SubmissionFactory(cgac_code=cgac2.cgac_code, frec_code=frec1.frec_code) sub3 = SubmissionFactory(cgac_code=cgac3.cgac_code, frec_code=None) sub4 = SubmissionFactory(cgac_code=cgac3.cgac_code, frec_code=frec2.frec_code) db_objects.extend([sub1, sub2, sub3, sub4]) # Setup agency user agency_user = UserFactory( name='Agency User', affiliations=[ UserAffiliation(user_affiliation_id=1, cgac=cgac1, permission_type_id=PERMISSION_TYPE_DICT['reader']), UserAffiliation(user_affiliation_id=2, cgac=cgac2, frec=frec1, permission_type_id=PERMISSION_TYPE_DICT['writer']), ]) db_objects.append(agency_user) monkeypatch.setattr(filters_helper, 'g', Mock(user=agency_user)) sess.add_all(db_objects) sess.commit() base_query = sess.query(Submission) # submissions should be filtered based on user access query = filters_helper.permissions_filter(base_query) expected_results = [sub1, sub2] results = set(query.all()) assert results == set(expected_results)
def test_get_sub_tiers_from_perms(database): """ Test getting sub tiers of agencies from the permissions provided """ cgacs = [CGACFactory(cgac_code=str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency "+str(i)) for i in range(3)] frec_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(3)] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers) database.session.commit() # Test non-admin, should have 1 and 2 results for cgac and frec respectively cgac_result, frec_result = get_sub_tiers_from_perms(False, [cgacs[0].cgac_id], [frecs[0].frec_id, frecs[1].frec_id]) assert cgac_result.count() == 1 assert frec_result.count() == 2 # Test non-admin with no permissions, should have 0 results for either cgac_result, frec_result = get_sub_tiers_from_perms(False, [], []) assert cgac_result.count() == 0 assert frec_result.count() == 0 # Test non-admin with permissions, should have 3 results for both (ignore permissions) cgac_result, frec_result = get_sub_tiers_from_perms(True, [cgacs[0].cgac_id], [frecs[0].frec_id, frecs[1].frec_id]) assert cgac_result.count() == 3 assert frec_result.count() == 3 # Test non-admin with no permissions, should have 3 results for both cgac_result, frec_result = get_sub_tiers_from_perms(True, [], []) assert cgac_result.count() == 3 assert frec_result.count() == 3
def test_organize_sub_tier_agencies(database): """ Test organization of passed sub tier agencies """ cgac = CGACFactory() frec_cgac = CGACFactory() frec = FRECFactory(cgac=frec_cgac) sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code='0', cgac=cgac, frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency 0"), SubTierAgencyFactory(sub_tier_agency_code='1', cgac=frec_cgac, frec=frec, is_frec=True, sub_tier_agency_name="Test Subtier Agency 1")] database.session.add_all([cgac] + [frec_cgac] + [frec] + sub_tiers) database.session.commit() # Test with no sub tiers results = organize_sub_tier_agencies([]) assert len(results["sub_tier_agency_list"]) == 0 # Test with just one sub tier passed in results = organize_sub_tier_agencies([sub_tiers[0]]) assert len(results["sub_tier_agency_list"]) == 1 assert results["sub_tier_agency_list"][0] == { "agency_name": '{}: {}'.format(cgac.agency_name, sub_tiers[0].sub_tier_agency_name), "agency_code": sub_tiers[0].sub_tier_agency_code, "priority": sub_tiers[0].priority} # Test with both sub tiers passed results = organize_sub_tier_agencies([sub_tiers[0], sub_tiers[1]]) assert len(results["sub_tier_agency_list"]) == 2
def test_list_agencies_superuser(domain_app, database): """ All agencies should be visible to website admins """ user = UserFactory(website_admin=True) cgacs = [CGACFactory(cgac_code=str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency " + str(i)) for i in range(3) ] frec_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(3) ] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers + [user]) database.session.commit() g.user = user result = domain_app.get('/v1/list_agencies/').data.decode('UTF-8') response = json.loads(result) result = {el['cgac_code'] for el in response['cgac_agency_list']} assert result == {'0', '1', '2'} # i.e. all of them result = {el['frec_code'] for el in response['frec_agency_list']} assert result == {'0', '1', '2'} # i.e. all of them
def test_list_agencies_limits(monkeypatch, user_constants, domain_app): """List agencies should limit to only the user's agencies""" sess = GlobalDB.db().session user = UserFactory() cgac = CGACFactory() frec_cgac = CGACFactory() frec = FRECFactory(cgac=frec_cgac) sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code='0', cgac=cgac, frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency 0"), SubTierAgencyFactory(sub_tier_agency_code='1', cgac=frec_cgac, frec=frec, is_frec=True, sub_tier_agency_name="Test Subtier Agency 1") ] user.affiliations = [ UserAffiliation(cgac=cgac, frec=None, permission_type_id=2), UserAffiliation(cgac=None, frec=frec, permission_type_id=2) ] sess.add_all([cgac] + [frec_cgac] + [frec] + sub_tiers + [user]) sess.commit() monkeypatch.setattr(domainRoutes, 'g', Mock(user=user)) result = domain_app.get('/v1/list_agencies/').data.decode('UTF-8') res = json.loads(result) assert len(res['cgac_agency_list']) == 1 assert len(res['frec_agency_list']) == 1 assert res['cgac_agency_list'][0]['agency_name'] == cgac.agency_name assert res['cgac_agency_list'][0]['cgac_code'] == cgac.cgac_code assert res['frec_agency_list'][0]['agency_name'] == frec.agency_name assert res['frec_agency_list'][0]['frec_code'] == frec.frec_code
def test_failure_populated_011_fr_entity_cgac(database): """ Tests that TAS for SF-133 are present in File A for CGAC submissions """ submission_id = randint(1000, 10000) tas, account_num, period, year, cgac_code, frec_code = 'some-tas', 1, 2, 2002, 'some-cgac-code', 'some-frec-code' cgac = CGACFactory(cgac_code=cgac_code, cgac_id=1) frec = FRECFactory(cgac_id=cgac.cgac_id, frec_code=frec_code, frec_id=1) sf1 = SF133Factory(tas=tas, period=period, fiscal_year=year, allocation_transfer_agency=None, agency_identifier='011', account_num=account_num) ts1 = TASFactory(account_num=account_num, fr_entity_type=frec_code) submission = SubmissionFactory(submission_id=submission_id, reporting_fiscal_period=period, reporting_fiscal_year=year, cgac_code=cgac_code, frec_code=None) ap = AppropriationFactory(tas='a-different-tas', submission_id=submission_id) errors = number_of_errors(_FILE, database, models=[cgac, frec, sf1, ts1, ap], submission=submission) assert errors == 1
def test_list_agencies_limits(domain_app, database): """ List agencies should limit to only the user's agencies and should not duplicate the same agency even if there are multiple instances of the same agency in the user permissions. """ user = UserFactory() cgac = CGACFactory() frec_cgac = CGACFactory() frec = FRECFactory(cgac=frec_cgac) sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code='0', cgac=cgac, frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency 0"), SubTierAgencyFactory(sub_tier_agency_code='1', cgac=frec_cgac, frec=frec, is_frec=True, sub_tier_agency_name="Test Subtier Agency 1")] user.affiliations = [UserAffiliation(cgac=cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['w']), UserAffiliation(cgac=cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['f']), UserAffiliation(cgac=None, frec=frec, permission_type_id=PERMISSION_SHORT_DICT['w']), UserAffiliation(cgac=None, frec=frec, permission_type_id=PERMISSION_SHORT_DICT['f'])] database.session.add_all([cgac] + [frec_cgac] + [frec] + sub_tiers + [user]) database.session.commit() g.user = user result = domain_app.get('/v1/list_agencies/').data.decode('UTF-8') res = json.loads(result) assert len(res['cgac_agency_list']) == 1 assert len(res['frec_agency_list']) == 1 assert res['cgac_agency_list'][0]['agency_name'] == cgac.agency_name assert res['cgac_agency_list'][0]['cgac_code'] == cgac.cgac_code assert res['frec_agency_list'][0]['agency_name'] == frec.agency_name assert res['frec_agency_list'][0]['frec_code'] == frec.frec_code
def test_get_submission_metadata_quarterly_dabs_cgac(database): """ Tests the get_submission_metadata function for quarterly dabs submissions """ sess = database.session now = datetime.datetime.utcnow() now_plus_10 = now + datetime.timedelta(minutes=10) cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency') frec_cgac = CGACFactory(cgac_code='999', agency_name='FREC CGAC') frec = FRECFactory(frec_code='0001', agency_name='FREC Agency', cgac=frec_cgac) sub = SubmissionFactory(submission_id=1, created_at=now, updated_at=now_plus_10, cgac_code=cgac.cgac_code, reporting_fiscal_period=3, reporting_fiscal_year=2017, is_quarter_format=True, publish_status_id=PUBLISH_STATUS_DICT['updated'], d2_submission=False, number_of_errors=40, number_of_warnings=200) # Job for submission job = JobFactory(submission_id=sub.submission_id, last_validated=now_plus_10, job_type=sess.query(JobType).filter_by(name='csv_record_validation').one(), job_status=sess.query(JobStatus).filter_by(name='finished').one(), file_type=sess.query(FileType).filter_by(name='appropriations').one(), number_of_rows=3, file_size=7655) job_2 = JobFactory(submission_id=sub.submission_id, last_validated=now_plus_10, job_type=sess.query(JobType).filter_by(name='csv_record_validation').one(), job_status=sess.query(JobStatus).filter_by(name='finished').one(), file_type=sess.query(FileType).filter_by(name='program_activity').one(), number_of_rows=7, file_size=12345) sess.add_all([cgac, frec_cgac, frec, sub, job, job_2]) sess.commit() # Test for Quarterly, updated DABS cgac submission expected_results = { 'cgac_code': cgac.cgac_code, 'frec_code': None, 'agency_name': cgac.agency_name, 'number_of_errors': 40, 'number_of_warnings': 200, 'number_of_rows': 10, 'total_size': 20000, 'created_on': now.strftime('%m/%d/%Y'), 'last_updated': now_plus_10.strftime("%Y-%m-%dT%H:%M:%S"), 'last_validated': now_plus_10.strftime('%m/%d/%Y'), 'reporting_period': 'Q1/2017', 'publish_status': 'updated', 'quarterly_submission': True, 'fabs_submission': False, 'fabs_meta': None } results = get_submission_metadata(sub) assert results == expected_results
def test_active_user_can_dabs_frec_submitter(database, monkeypatch, user_constants): user_cgac, other_cgac = [CGACFactory() for _ in range(2)] user_frec, other_frec = FRECFactory(cgac=user_cgac), FRECFactory( cgac=other_cgac) user_submitter = UserFactory(affiliations=[ UserAffiliation(frec=user_frec, permission_type_id=PERMISSION_TYPE_DICT['submitter']) ]) database.session.add_all( [user_cgac, other_cgac, user_frec, other_frec, user_submitter]) database.session.commit() monkeypatch.setattr(permissions, 'g', Mock(user=user_submitter)) # has permission level, but wrong agency assert not permissions.active_user_can('reader', frec_code=other_frec.frec_code) assert not permissions.active_user_can('writer', frec_code=other_frec.frec_code) assert not permissions.active_user_can('submitter', frec_code=other_frec.frec_code) # has agency, but not permission level assert not permissions.active_user_can('editfabs', cgac_code=user_frec.frec_code) assert not permissions.active_user_can('fabs', cgac_code=user_frec.frec_code) # right agency, right permission assert permissions.active_user_can('reader', frec_code=user_frec.frec_code) assert permissions.active_user_can('writer', frec_code=user_frec.frec_code) assert permissions.active_user_can('submitter', frec_code=user_frec.frec_code) # wrong agency, but superuser user_submitter.website_admin = True assert permissions.active_user_can('submitter', frec_code=other_frec.frec_code)
def setUpClass(cls): """Set up class-wide resources like users.""" super(DomainTests, cls).setUpClass() with create_app().app_context(): sess = GlobalDB.db().session user = User() r_cgac = CGACFactory() w_cgac = CGACFactory() s_frec_cgac = CGACFactory() s_frec = FRECFactory(cgac=s_frec_cgac) e_frec_cgac = CGACFactory() e_frec = FRECFactory(cgac=e_frec_cgac) f_cgac = CGACFactory() user.affiliations = [ UserAffiliation(cgac=r_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['r']), UserAffiliation(cgac=w_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['w']), UserAffiliation(cgac=None, frec=s_frec, permission_type_id=PERMISSION_SHORT_DICT['s']), UserAffiliation(cgac=None, frec=e_frec, permission_type_id=PERMISSION_SHORT_DICT['e']), UserAffiliation(cgac=f_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['f']) ] sess.add_all([ r_cgac, w_cgac, s_frec_cgac, s_frec, e_frec_cgac, e_frec, f_cgac ]) sess.commit()
def test_get_submission_metadata_published_fabs(database): """ Tests the get_submission_metadata function for published fabs submissions """ sess = database.session now = datetime.datetime.utcnow() now_plus_10 = now + datetime.timedelta(minutes=10) start_date = datetime.date(2000, 1, 1) cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency') frec_cgac = CGACFactory(cgac_code='999', agency_name='FREC CGAC') frec = FRECFactory(frec_code='0001', agency_name='FREC Agency', cgac=frec_cgac) sub = SubmissionFactory(submission_id=5, created_at=now, updated_at=now, cgac_code=cgac.cgac_code, reporting_fiscal_period=5, reporting_fiscal_year=2010, is_quarter_format=False, publish_status_id=PUBLISH_STATUS_DICT['published'], d2_submission=True, reporting_start_date=start_date, number_of_errors=0, number_of_warnings=2) # Data for FABS dafa_1 = DetachedAwardFinancialAssistanceFactory(submission_id=sub.submission_id, is_valid=True) dafa_2 = DetachedAwardFinancialAssistanceFactory(submission_id=sub.submission_id, is_valid=False) cert_hist = CertifyHistoryFactory(submission=sub, created_at=now_plus_10) sess.add_all([cgac, frec_cgac, frec, sub, dafa_1, dafa_2, cert_hist]) sess.commit() expected_results = { 'cgac_code': cgac.cgac_code, 'frec_code': None, 'agency_name': cgac.agency_name, 'number_of_errors': 0, 'number_of_warnings': 2, 'number_of_rows': 0, 'total_size': 0, 'created_on': now.strftime('%m/%d/%Y'), 'last_updated': now.strftime("%Y-%m-%dT%H:%M:%S"), 'last_validated': '', 'reporting_period': start_date.strftime('%m/%Y'), 'publish_status': 'published', 'quarterly_submission': False, 'certified_submission': None, 'fabs_submission': True, 'fabs_meta': { 'publish_date': now_plus_10.strftime('%-I:%M%p %m/%d/%Y'), 'published_file': None, 'total_rows': 2, 'valid_rows': 1 } } results = get_submission_metadata(sub) assert results == expected_results
def test_get_accessible_agencies(database): """ Test listing all the agencies (CGAC and FREC) that are accessible based on permissions given """ cgacs = [ CGACFactory(cgac_code=str(i), agency_name="Test Agency " + str(i)) for i in range(3) ] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency " + str(i)) for i in range(3) ] frec_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(3) ] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers) database.session.commit() # Test one CGAC and 2 FRECs, have to decode it because we send it back as a response already results = get_accessible_agencies([cgac_sub_tiers[0]], [frec_sub_tiers[0], frec_sub_tiers[2]]) frec_code_result = {el["frec_code"] for el in results["frec_agency_list"]} frec_name_result = { el["agency_name"] for el in results["frec_agency_list"] } assert len(results["cgac_agency_list"]) == 1 assert len(results["frec_agency_list"]) == 2 assert results["cgac_agency_list"][0]["agency_name"] == cgacs[ 0].agency_name assert results["cgac_agency_list"][0]["cgac_code"] == cgacs[0].cgac_code assert frec_name_result == {frecs[0].agency_name, frecs[2].agency_name} assert frec_code_result == {frecs[0].frec_code, frecs[2].frec_code} # Test when there are no FRECs results = get_accessible_agencies([cgac_sub_tiers[0]], []) assert len(results["cgac_agency_list"]) == 1 assert len(results["frec_agency_list"]) == 0
def test_get_accessible_agencies(database): """ Test listing all the agencies (CGAC and FREC) that are accessible based on permissions given """ # The first cgac/frec don't have sub tiers associated, they should still show up when affiliations are present cgacs = [CGACFactory(cgac_code=str(i), agency_name="Test Agency " + str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency C" + str(i)) for i in range(1, 3)] frec_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency F" + str(i)) for i in range(1, 3)] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers) database.session.commit() user = UserFactory(affiliations=[ UserAffiliation(user_affiliation_id=1, cgac=cgacs[0], frec=None, permission_type_id=PERMISSION_TYPE_DICT['writer']), UserAffiliation(user_affiliation_id=2, cgac=None, frec=frecs[1], permission_type_id=PERMISSION_TYPE_DICT['reader']), UserAffiliation(user_affiliation_id=3, cgac=None, frec=frecs[2], permission_type_id=PERMISSION_TYPE_DICT['reader']) ]) database.session.add(user) database.session.commit() g.user = user # Test one CGAC and 2 FRECs, have to decode it because we send it back as a response already results = get_accessible_agencies() frec_code_result = {el["frec_code"] for el in results["frec_agency_list"]} frec_name_result = {el["agency_name"] for el in results["frec_agency_list"]} assert len(results["cgac_agency_list"]) == 1 assert len(results["frec_agency_list"]) == 2 assert results["cgac_agency_list"][0]["agency_name"] == cgacs[0].agency_name assert results["cgac_agency_list"][0]["cgac_code"] == cgacs[0].cgac_code assert frec_name_result == {frecs[1].agency_name, frecs[2].agency_name} assert frec_code_result == {frecs[1].frec_code, frecs[2].frec_code} # Test when user is website admin, should return everything, but only 2 frecs because only 2 of the 3 have the # frec flag user.affiliations = [] user.website_admin = True results = get_accessible_agencies() assert len(results["cgac_agency_list"]) == 3 assert len(results["frec_agency_list"]) == 2
def test_get_all_agencies(database): """ Test printing out all agencies, FRECs only retrieved if they have a sub tier, CGACs always """ cgacs = [CGACFactory(cgac_code=str(i), agency_name="Test Agency " + str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(6, 9)] cgac_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency " + str(i)) for i in range(2)] frec_sub_tiers = [SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(2)] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers) database.session.commit() results = get_all_agencies() cgac_result = {el["cgac_code"] for el in results["agency_list"]} frec_result = {el["frec_code"] for el in results["shared_agency_list"]} assert len(results["agency_list"]) == 3 assert len(results["shared_agency_list"]) == 2 assert cgac_result == {"0", "1", "2"} assert frec_result == {"6", "7"}
def test_list_sub_tier_agencies_admin(domain_app, database): """ List all sub tiers that a user has FABS permissions for """ user = UserFactory(website_admin=True) cgacs = [CGACFactory(cgac_code=str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency " + str(i)) for i in range(3) ] frec_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(3) ] user.affiliations = [ UserAffiliation(cgac=cgacs[0], frec=None, permission_type_id=PERMISSION_SHORT_DICT['f']), UserAffiliation(cgac=None, frec=frecs[2], permission_type_id=PERMISSION_SHORT_DICT['f']) ] database.session.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers + [user]) database.session.commit() g.user = user result = domain_app.get('/v1/list_sub_tier_agencies/').data.decode('UTF-8') response = json.loads(result) result = {el['agency_code'] for el in response['sub_tier_agency_list']} assert len(response["sub_tier_agency_list"] ) == 6 # All of them, ignores affiliations assert result == {'0', '1', '2', '3', '4', '5'} # All of them, ignores affiliations
def test_get_submission_metadata_unpublished_fabs(database): """ Tests the get_submission_metadata function for unpublished fabs submissions """ sess = database.session now = datetime.datetime.utcnow() start_date = datetime.date(2000, 1, 1) cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency') frec_cgac = CGACFactory(cgac_code='999', agency_name='FREC CGAC') frec = FRECFactory(frec_code='0001', agency_name='FREC Agency', cgac=frec_cgac) sub = SubmissionFactory(submission_id=4, created_at=now, updated_at=now, cgac_code=cgac.cgac_code, reporting_fiscal_period=1, reporting_fiscal_year=2015, is_quarter_format=False, publish_status_id=PUBLISH_STATUS_DICT['unpublished'], d2_submission=True, reporting_start_date=start_date, number_of_errors=4, number_of_warnings=1) sess.add_all([cgac, frec_cgac, frec, sub]) sess.commit() expected_results = { 'cgac_code': cgac.cgac_code, 'frec_code': None, 'agency_name': cgac.agency_name, 'number_of_errors': 4, 'number_of_warnings': 1, 'number_of_rows': 0, 'total_size': 0, 'created_on': now.strftime('%m/%d/%Y'), 'last_updated': now.strftime("%Y-%m-%dT%H:%M:%S"), 'last_validated': '', 'reporting_period': start_date.strftime('%m/%Y'), 'publish_status': 'unpublished', 'quarterly_submission': False, 'certified_submission': None, 'fabs_submission': True, 'fabs_meta': {'publish_date': None, 'published_file': None, 'total_rows': 0, 'valid_rows': 0} } results = get_submission_metadata(sub) assert results == expected_results
def test_get_submission_metadata_quarterly_dabs_frec(database): """ Tests the get_submission_metadata function for quarterly dabs submissions frec """ sess = database.session now = datetime.datetime.utcnow() frec_cgac = CGACFactory(cgac_code='999', agency_name='FREC CGAC') frec = FRECFactory(frec_code='0001', agency_name='FREC Agency', cgac=frec_cgac) sub = SubmissionFactory(submission_id=2, created_at=now, updated_at=now, cgac_code=None, frec_code=frec.frec_code, reporting_fiscal_period=6, reporting_fiscal_year=2010, is_quarter_format=True, publish_status_id=PUBLISH_STATUS_DICT['published'], d2_submission=False, number_of_errors=0, number_of_warnings=0) sess.add_all([frec_cgac, frec, sub]) sess.commit() expected_results = { 'cgac_code': None, 'frec_code': frec.frec_code, 'agency_name': frec.agency_name, 'number_of_errors': 0, 'number_of_warnings': 0, 'number_of_rows': 0, 'total_size': 0, 'created_on': now.strftime('%m/%d/%Y'), 'last_updated': now.strftime("%Y-%m-%dT%H:%M:%S"), 'last_validated': '', 'reporting_period': 'Q2/2010', 'publish_status': 'published', 'quarterly_submission': True, 'certified_submission': None, 'fabs_submission': False, 'fabs_meta': None } results = get_submission_metadata(sub) assert results == expected_results
def test_list_agencies_all(monkeypatch, user_constants, domain_app): """All agencies should be visible to website admins""" sess = GlobalDB.db().session user = UserFactory() cgacs = [CGACFactory(cgac_code=str(i)) for i in range(3)] frec_cgac = CGACFactory() frecs = [FRECFactory(frec_code=str(i), cgac=frec_cgac) for i in range(3)] cgac_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(i), cgac=cgacs[i], frec=None, is_frec=False, sub_tier_agency_name="Test Subtier Agency " + str(i)) for i in range(3) ] frec_sub_tiers = [ SubTierAgencyFactory(sub_tier_agency_code=str(3 + i), cgac=frec_cgac, frec=frecs[i], is_frec=True, sub_tier_agency_name="Test Subtier Agency " + str(3 + i)) for i in range(3) ] user.affiliations = [ UserAffiliation(cgac=cgacs[0], frec=frecs[0], permission_type_id=2) ] sess.add_all(cgacs + [frec_cgac] + frecs + cgac_sub_tiers + frec_sub_tiers + [user]) sess.commit() monkeypatch.setattr(domainRoutes, 'g', Mock(user=user)) result = domain_app.get('/v1/list_all_agencies/').data.decode('UTF-8') response = json.loads(result) result = {el['cgac_code'] for el in response['agency_list']} assert result == {'0', '1', '2'} # i.e. all of them result = {el['frec_code'] for el in response['shared_agency_list']} assert result == {'0', '1', '2'} # i.e. all of them
def test_success(database): """ Tests that TAS with no ATA or matching ATA pass. """ sub = SubmissionFactory(cgac_code='abc') cgac = CGACFactory(cgac_code='abc') tas = TASFactory(financial_indicator2='f') # Matching ATA ap1 = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='abc', adjustments_to_unobligated_cpe=15) # Blank ATA ap2 = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='', adjustments_to_unobligated_cpe=15) ap3 = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency=None, adjustments_to_unobligated_cpe=15) # Non-matching ATA with all monetary values 0 (with one None for good measure) ap4 = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='Not a match', adjustments_to_unobligated_cpe=0, budget_authority_appropria_cpe=0, borrowing_authority_amount_cpe=0, contract_authority_amount_cpe=None, spending_authority_from_of_cpe=0, other_budgetary_resources_cpe=0, total_budgetary_resources_cpe=0, gross_outlay_amount_by_tas_cpe=0, obligations_incurred_total_cpe=0, deobligations_recoveries_r_cpe=0, unobligated_balance_cpe=0, status_of_budgetary_resour_cpe=0) # Non-matching ATA with financial_indicator2 of F ap5 = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='Not a match', account_num=tas.account_num, adjustments_to_unobligated_cpe=15) assert number_of_errors(_FILE, database, submission=sub, models=[cgac, tas, ap1, ap2, ap3, ap4, ap5]) == 0 cgac = CGACFactory(cgac_code='123') database.session.add(cgac) database.session.commit() frec = FRECFactory(frec_code='abcd', cgac_id=cgac.cgac_id) sub = SubmissionFactory(cgac_code=None, frec_code=frec.frec_code) # Matching ATA for a FREC ap = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='123', adjustments_to_unobligated_cpe=15) assert number_of_errors(_FILE, database, submission=sub, models=[frec, ap]) == 0 # Accounting for CGAC 097 (021 is allowed) dod_cgac = CGACFactory(cgac_code='097') database.session.add(dod_cgac) database.session.commit() frec = FRECFactory(frec_code='abcde', cgac_id=dod_cgac.cgac_id) sub = SubmissionFactory(cgac_code=None, frec_code=frec.frec_code) # Matching ATA for a FREC ap = AppropriationFactory(submission_id=sub.submission_id, allocation_transfer_agency='021', adjustments_to_unobligated_cpe=15) assert number_of_errors(_FILE, database, submission=sub, models=[frec, ap]) == 0
def initialize_db_values(db, cfda_title=None, cgac_code=None, frec_code=None, use_frec=False): """ Initialize the values in the DB that can be used throughout the tests """ if cgac_code: cgac = CGACFactory(cgac_code=cgac_code, agency_name="Test CGAC Agency") else: cgac = CGACFactory() if frec_code: frec = FRECFactory(frec_code=frec_code, agency_name="Test FREC Agency", cgac=cgac) else: frec = FRECFactory(cgac=cgac) db.session.add_all([cgac, frec]) db.session.commit() cfda_number = CFDAProgramFactory(program_number=12.345, program_title=cfda_title) sub_tier = SubTierAgencyFactory(sub_tier_agency_code="1234", cgac=cgac, frec=frec, is_frec=use_frec, sub_tier_agency_name="Test Subtier Agency") state = StatesFactory(state_code="NY", state_name="New York") zip_code_1 = ZipsFactory(zip5="12345", zip_last4="6789", state_abbreviation=state.state_code, county_number="001", congressional_district_no="01") zip_code_2 = ZipsFactory(zip5="12345", zip_last4="4321", state_abbreviation=state.state_code, county_number="001", congressional_district_no="02") zip_code_3 = ZipsFactory(zip5="54321", zip_last4="4321", state_abbreviation=state.state_code, county_number="001", congressional_district_no="05") zip_code_4 = ZipsFactory(zip5="98765", zip_last4="4321", state_abbreviation=state.state_code, county_number="001", congressional_district_no=None) zip_city = ZipCityFactory(zip_code=zip_code_1.zip5, city_name="Test Zip City") zip_city_2 = ZipCityFactory(zip_code=zip_code_3.zip5, city_name="Test Zip City 2") zip_city_3 = ZipCityFactory(zip_code=zip_code_4.zip5, city_name="Test Zip City 3") county_code = CountyCodeFactory(state_code=state.state_code, county_number=zip_code_1.county_number, county_name="Test County") city_code = CityCodeFactory(feature_name="Test City", city_code="00001", state_code=state.state_code, county_number=zip_code_1.county_number, county_name="Test City County") contracting_office = FPDSContractingOfficeFactory( contracting_office_code='033103', contracting_office_name='Office') country_code = CountryCodeFactory(country_code='USA', country_name='United States of America') db.session.add_all([ sub_tier, state, cfda_number, zip_code_1, zip_code_2, zip_code_3, zip_code_4, zip_city, zip_city_2, zip_city_3, county_code, city_code, contracting_office, country_code ]) db.session.commit()
def test_list_agencies_perm_params(domain_app, database): """ Users should be able to filter their affiliations based on the arguments provided """ user = UserFactory() r_cgac = CGACFactory() w_cgac = CGACFactory() s_frec_cgac = CGACFactory() s_frec = FRECFactory(cgac=s_frec_cgac) e_frec_cgac = CGACFactory() e_frec = FRECFactory(cgac=e_frec_cgac) f_cgac = CGACFactory() user.affiliations = [ UserAffiliation(cgac=r_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['r']), UserAffiliation(cgac=w_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['w']), UserAffiliation(cgac=None, frec=s_frec, permission_type_id=PERMISSION_SHORT_DICT['s']), UserAffiliation(cgac=None, frec=e_frec, permission_type_id=PERMISSION_SHORT_DICT['e']), UserAffiliation(cgac=f_cgac, frec=None, permission_type_id=PERMISSION_SHORT_DICT['f']) ] database.session.add_all( [r_cgac, w_cgac, s_frec_cgac, s_frec, e_frec_cgac, e_frec, f_cgac]) database.session.commit() g.user = user def call_list_agencies(perm_level='reader', perm_type='mixed'): result = domain_app.get('/v1/list_agencies/?perm_level={}&perm_type={}'.format(perm_level, perm_type))\ .data.decode('UTF-8') resp = json.loads(result) cgac_codes = [ agency['cgac_code'] for agency in resp['cgac_agency_list'] ] frec_codes = [ agency['frec_code'] for agency in resp['frec_agency_list'] ] return cgac_codes, frec_codes default_cgacs, default_frecs = call_list_agencies() assert {r_cgac.cgac_code, w_cgac.cgac_code, f_cgac.cgac_code} == set(default_cgacs) assert {s_frec.frec_code, e_frec.frec_code} == set(default_frecs) writer_cgacs, writer_frecs = call_list_agencies(perm_level='writer') assert {w_cgac.cgac_code, f_cgac.cgac_code} == set(writer_cgacs) assert {s_frec.frec_code, e_frec.frec_code} == set(writer_frecs) submitter_cgacs, submitter_frecs = call_list_agencies( perm_level='submitter') assert {f_cgac.cgac_code} == set(submitter_cgacs) assert {s_frec.frec_code} == set(submitter_frecs) dabs_cgacs, dabs_frecs = call_list_agencies(perm_type='dabs') assert {r_cgac.cgac_code, w_cgac.cgac_code} == set(dabs_cgacs) assert {s_frec.frec_code} == set(dabs_frecs) fabs_cgacs, fabs_frecs = call_list_agencies(perm_type='fabs') assert {f_cgac.cgac_code} == set(fabs_cgacs) assert {e_frec.frec_code} == set(fabs_frecs) # mix mix_cgacs, mix_frecs = call_list_agencies(perm_level='submitter', perm_type='fabs') assert {f_cgac.cgac_code} == set(mix_cgacs) assert set() == set(mix_frecs)
def test_agency_filter(database): sess = database.session db_objects = [] # Setup agencies cgac1 = CGACFactory(cgac_code='089', agency_name='CGAC') cgac2 = CGACFactory(cgac_code='011', agency_name='CGAC Associated with FREC') cgac3 = CGACFactory(cgac_code='091', agency_name='Other CGAC Associated with FREC') frec1 = FRECFactory(cgac=cgac2, frec_code='1125', agency_name='FREC 1') frec2 = FRECFactory(cgac=cgac3, frec_code='0923', agency_name='FREC 2') db_objects.extend([cgac1, cgac2, cgac3, frec1, frec2]) # Setup submissions sub1 = SubmissionFactory(cgac_code=cgac1.cgac_code, frec_code=None) sub2 = SubmissionFactory(cgac_code=cgac2.cgac_code, frec_code=frec1.frec_code) sub3 = SubmissionFactory(cgac_code=cgac3.cgac_code, frec_code=None) sub4 = SubmissionFactory(cgac_code=cgac3.cgac_code, frec_code=frec2.frec_code) db_objects.extend([sub1, sub2, sub3, sub4]) sess.add_all(db_objects) sess.commit() base_query = sess.query(Submission) # no agency list, no filtering agency_list = [] query = filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) expected_results = [sub1, sub2, sub3, sub4] results = query.all() assert set(results) == set(expected_results) # filter for CGACS agency_list = ['011'] query = filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) expected_results = [sub2] results = list(query.all()) assert results == expected_results # filter for FRECS agency_list = ['0923'] query = filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) expected_results = [sub4] results = list(query.all()) assert results == expected_results # filter for both agency_list = ['011', '0923'] query = filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) expected_results = [sub2, sub4] results = set(query.all()) assert results == set(expected_results) # throw in one that doesn't fit the agency format agency_list = ['089', '1125', '3'] expected_response = 'All codes in the agency_codes filter must be valid agency codes' with pytest.raises(ResponseException) as resp_except: filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) assert resp_except.value.status == 400 assert str(resp_except.value) == expected_response # throw in one that just doesn't exist agency_list = ['089', '1125', '012'] with pytest.raises(ResponseException) as resp_except: filters_helper.agency_filter(sess, base_query, cgac_model=Submission, frec_model=Submission, agency_list=agency_list) assert resp_except.value.status == 400 assert str(resp_except.value) == expected_response
def setup_tests(sess): db_objects = [] # Setup agencies cgac1 = CGACFactory(cgac_code='097', agency_name='CGAC') frec = FRECFactory(cgac=cgac1, frec_code='1125', agency_name='FREC') db_objects.extend([cgac1, frec]) # Setup rules rsql_a1 = RuleSql(rule_sql='', rule_label='A1', rule_error_message='A1 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['A'], rule_severity_id=RULE_SEVERITY_DICT['warning'], rule_cross_file_flag=False, target_file_id=None) rsql_a2 = RuleSql(rule_sql='', rule_label='A2', rule_error_message='A2 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['A'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) rsql_a3 = RuleSql(rule_sql='', rule_label='A3', rule_error_message='A3 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['A'], rule_severity_id=RULE_SEVERITY_DICT['warning'], rule_cross_file_flag=False, target_file_id=None) rsql_a4 = RuleSql(rule_sql='', rule_label='A4', rule_error_message='A4 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['A'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) rsql_b1 = RuleSql(rule_sql='', rule_label='B1', rule_error_message='B1 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['B'], rule_severity_id=RULE_SEVERITY_DICT['warning'], rule_cross_file_flag=False, target_file_id=None) rsql_b2 = RuleSql(rule_sql='', rule_label='B2', rule_error_message='B2 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['B'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) rsql_b3 = RuleSql(rule_sql='', rule_label='B3', rule_error_message='B3 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['B'], rule_severity_id=RULE_SEVERITY_DICT['warning'], rule_cross_file_flag=False, target_file_id=None) rsql_b4 = RuleSql(rule_sql='', rule_label='B4', rule_error_message='B4 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['B'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) rsql_c1 = RuleSql(rule_sql='', rule_label='C1', rule_error_message='C1 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['C'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) rsql_c2 = RuleSql(rule_sql='', rule_label='C2', rule_error_message='C2 Description', query_name='', file_id=FILE_TYPE_DICT_LETTER_ID['C'], rule_severity_id=RULE_SEVERITY_DICT['fatal'], rule_cross_file_flag=False, target_file_id=None) sess.add_all([ rsql_a1, rsql_a2, rsql_a3, rsql_a4, rsql_b1, rsql_b2, rsql_b3, rsql_b4, rsql_c1, rsql_c2 ]) # Setup default rules load_default_rule_settings(sess) sess.add_all(db_objects) sess.commit()
def test_current_user_can(database, monkeypatch, user_constants): # Test CGAC DABS permissions user_cgac, other_cgac = [CGACFactory() for _ in range(2)] user_one = UserFactory(affiliations=[ UserAffiliation(cgac=user_cgac, permission_type_id=PERMISSION_TYPE_DICT['writer']) ]) database.session.add_all([user_cgac, other_cgac, user_one]) database.session.commit() monkeypatch.setattr(permissions, 'g', Mock(user=user_one)) # has permission level, but wrong agency assert not permissions.current_user_can('reader', other_cgac.cgac_code, None) # has agency, but not permission level assert not permissions.current_user_can('submitter', user_cgac.cgac_code, None) # right agency, right permission assert permissions.current_user_can('writer', user_cgac.cgac_code, None) assert permissions.current_user_can('reader', user_cgac.cgac_code, None) # wrong permission level, wrong agency, but superuser user_one.website_admin = True assert permissions.current_user_can('submitter', other_cgac.cgac_code, None) # Test FREC DABS permissions user_frec, other_frec = [FRECFactory(cgac=user_cgac) for _ in range(2)] user_two = UserFactory(affiliations=[ UserAffiliation(frec=user_frec, permission_type_id=PERMISSION_TYPE_DICT['writer']) ]) database.session.add_all([user_frec, other_frec, user_two]) database.session.commit() monkeypatch.setattr(permissions, 'g', Mock(user=user_two)) # has permission level, but wrong agency assert not permissions.current_user_can('reader', None, other_frec.frec_code) # has agency, but not permission level assert not permissions.current_user_can('submitter', None, user_frec.frec_code) # right agency, right permission assert permissions.current_user_can('writer', None, user_frec.frec_code) assert permissions.current_user_can('reader', None, user_frec.frec_code) # wrong permission level, wrong agency, but superuser user_two.website_admin = True assert permissions.current_user_can('submitter', None, other_frec.frec_code) # Test FABS permissions user_three = UserFactory(affiliations=[ UserAffiliation(cgac=user_cgac, permission_type_id=PERMISSION_SHORT_DICT['f']) ]) database.session.add(user_three) database.session.commit() monkeypatch.setattr(permissions, 'g', Mock(user=user_three)) # has permission level, but wrong agency assert not permissions.current_user_can('fabs', other_cgac.cgac_code, None) # has agency, but not permission level assert not permissions.current_user_can('submitter', user_cgac.cgac_code, None) # right agency, right permission assert permissions.current_user_can('fabs', user_cgac.cgac_code, None) # wrong permission level, wrong agency, but superuser user_three.website_admin = True assert permissions.current_user_can('submitter', other_cgac.cgac_code, None)
def test_set_max_perms(database, monkeypatch): """Verify that we get the _highest_ permission within our CGAC""" cgac_abc = CGACFactory(cgac_code='ABC') cgac_def = CGACFactory(cgac_code='DEF') frec_abc = FRECFactory(frec_code='ABCD', cgac=cgac_abc) frec_def = FRECFactory(frec_code='EFGH', cgac=cgac_abc) user = UserFactory() database.session.add_all([cgac_abc, cgac_def, frec_abc, frec_def, user]) database.session.commit() monkeypatch.setitem(account_handler.CONFIG_BROKER, 'parent_group', 'prefix') # test creating permission from string account_handler.set_max_perms(user, 'prefix-CGAC_ABC-PERM_W') database.session.commit() # populate ids assert len(user.affiliations) == 1 affil = user.affiliations[0] assert affil.cgac_id == cgac_abc.cgac_id assert affil.permission_type_id == PERMISSION_TYPE_DICT['writer'] # test creating max CGAC permission from two strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-PERM_R,prefix-CGAC_ABC-PERM_S') database.session.commit() # populate ids assert len(user.affiliations) == 1 affil = user.affiliations[0] assert affil.cgac_id == cgac_abc.cgac_id assert affil.permission_type_id == PERMISSION_TYPE_DICT['submitter'] # test creating two CGAC permissions with two strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-PERM_R,prefix-CGAC_DEF-PERM_S') database.session.commit() assert len(user.affiliations) == 2 affiliations = list( sorted(user.affiliations, key=lambda a: a.cgac.cgac_code)) abc_aff, def_aff = affiliations assert abc_aff.cgac.cgac_code == 'ABC' assert abc_aff.frec is None assert abc_aff.permission_type_id == PERMISSION_TYPE_DICT['reader'] assert def_aff.cgac.cgac_code == 'DEF' assert def_aff.frec is None assert def_aff.permission_type_id == PERMISSION_TYPE_DICT['submitter'] # test creating max FREC permission from two strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-FREC_ABCD-PERM_R,prefix-CGAC_ABC-FREC_ABCD-PERM_S') database.session.commit() assert len(user.affiliations) == 2 frec_affils = [ affil for affil in user.affiliations if affil.frec is not None ] assert frec_affils[0].cgac is None assert frec_affils[0].frec.frec_code == 'ABCD' assert frec_affils[0].permission_type_id == PERMISSION_TYPE_DICT[ 'submitter'] cgac_affils = [ affil for affil in user.affiliations if affil.cgac is not None ] assert cgac_affils[0].cgac.cgac_code == 'ABC' assert cgac_affils[0].frec is None assert cgac_affils[0].permission_type_id == PERMISSION_TYPE_DICT['reader'] # test creating two FREC permissions from two strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-FREC_ABCD-PERM_R,prefix-CGAC_ABC-FREC_EFGH-PERM_S') database.session.commit() assert len(user.affiliations) == 3 frec_affils = [ affil for affil in user.affiliations if affil.frec is not None ] frec_affiliations = list( sorted(frec_affils, key=lambda a: a.frec.frec_code)) abcd_aff, efgh_aff = frec_affiliations assert abcd_aff.cgac is None assert abcd_aff.frec.frec_code == 'ABCD' assert abcd_aff.permission_type_id == PERMISSION_TYPE_DICT['reader'] assert efgh_aff.cgac is None assert efgh_aff.frec.frec_code == 'EFGH' assert efgh_aff.permission_type_id == PERMISSION_TYPE_DICT['submitter'] cgac_affils = [ affil for affil in user.affiliations if affil.cgac is not None ] assert cgac_affils[0].cgac.cgac_code == 'ABC' assert cgac_affils[0].frec is None assert cgac_affils[0].permission_type_id == PERMISSION_TYPE_DICT['reader'] # test creating one CGAC and one FREC permission from two strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-PERM_S,prefix-CGAC_DEF-FREC_ABCD-PERM_R') database.session.commit() assert len(user.affiliations) == 3 frec_affils = [ affil for affil in user.affiliations if affil.frec is not None ] assert frec_affils[0].cgac is None assert frec_affils[0].frec.frec_code == 'ABCD' assert frec_affils[0].permission_type_id == PERMISSION_TYPE_DICT['reader'] cgac_affils = [ affil for affil in user.affiliations if affil.cgac is not None ] cgac_affiliations = list( sorted(cgac_affils, key=lambda a: a.cgac.cgac_code)) abc_aff, def_aff = cgac_affiliations assert abc_aff.cgac.cgac_code == 'ABC' assert abc_aff.frec is None assert abc_aff.permission_type_id == PERMISSION_TYPE_DICT['submitter'] assert def_aff.cgac.cgac_code == 'DEF' assert def_aff.frec is None assert def_aff.permission_type_id == PERMISSION_TYPE_DICT['reader'] # test creating max DABS and FABS CGAC permissions from three strings account_handler.set_max_perms( user, 'prefix-CGAC_ABC-PERM_R,prefix-CGAC_ABC-PERM_S,prefix-CGAC_ABC-PERM_F') database.session.commit() assert len(user.affiliations) == 2 affiliations = list( sorted(user.affiliations, key=lambda a: a.permission_type_id)) dabs_aff, fabs_aff = affiliations assert dabs_aff.cgac.cgac_code == 'ABC' assert dabs_aff.frec is None assert dabs_aff.permission_type_id == PERMISSION_TYPE_DICT['submitter'] assert fabs_aff.cgac.cgac_code == 'ABC' assert fabs_aff.frec is None assert fabs_aff.permission_type_id == PERMISSION_SHORT_DICT['f'] # test creating max DABS and FABS FREC permissions from three strings perms_string = 'prefix-CGAC_ABC-FREC_ABCD-PERM_R,prefix-CGAC_ABC-FREC_ABCD-PERM_S,prefix-CGAC_ABC-FREC_ABCD-PERM_F' account_handler.set_max_perms(user, perms_string) database.session.commit() assert len(user.affiliations) == 3 frec_affils = [ affil for affil in user.affiliations if affil.frec is not None ] frec_affiliations = list( sorted(frec_affils, key=lambda a: a.permission_type_id)) dabs_aff, fabs_aff = frec_affiliations assert dabs_aff.cgac is None assert dabs_aff.frec.frec_code == 'ABCD' assert dabs_aff.permission_type_id == PERMISSION_TYPE_DICT['submitter'] assert fabs_aff.cgac is None assert fabs_aff.frec.frec_code == 'ABCD' assert fabs_aff.permission_type_id == PERMISSION_SHORT_DICT['f'] cgac_affils = [ affil for affil in user.affiliations if affil.cgac is not None ] assert cgac_affils[0].cgac.cgac_code == 'ABC' assert cgac_affils[0].frec is None assert cgac_affils[0].permission_type_id == PERMISSION_TYPE_DICT['reader'] # test creating DABS and FABS CGAC permissions from service accounts perms_string = 'prefix-CGAC_ABC-PERM_W' account_handler.set_max_perms(user, perms_string, service_account_flag=True) database.session.commit() assert len(user.affiliations) == 2 abc_aff, def_aff = list( sorted(user.affiliations, key=lambda a: a.permission_type_id)) assert abc_aff.cgac.cgac_code == 'ABC' assert abc_aff.frec is None assert abc_aff.permission_type_id == PERMISSION_TYPE_DICT['writer'] assert def_aff.cgac.cgac_code == 'ABC' assert def_aff.frec is None assert def_aff.permission_type_id == PERMISSION_SHORT_DICT['e'] # test creating DABS and FABS FREC permissions from service accounts perms_string = 'prefix-CGAC_ABC-FREC_ABCD-PERM_F' account_handler.set_max_perms(user, perms_string, service_account_flag=True) database.session.commit() assert len(user.affiliations) == 3 frec_affils = [ affil for affil in user.affiliations if affil.frec is not None ] frec_affiliations = list( sorted(frec_affils, key=lambda a: a.permission_type_id)) dabs_aff, fabs_aff = frec_affiliations assert dabs_aff.cgac is None assert dabs_aff.frec.frec_code == 'ABCD' assert dabs_aff.permission_type_id == PERMISSION_TYPE_DICT['writer'] assert fabs_aff.cgac is None assert fabs_aff.frec.frec_code == 'ABCD' assert fabs_aff.permission_type_id == PERMISSION_SHORT_DICT['e'] cgac_affils = [ affil for affil in user.affiliations if affil.cgac is not None ] assert cgac_affils[0].cgac.cgac_code == 'ABC' assert cgac_affils[0].frec is None assert cgac_affils[0].permission_type_id == PERMISSION_TYPE_DICT['reader']