def test_pay_request_is_correct_with_branch_name(session, keycloak_mock): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" user = factory_user_model() with patch.object(RestService, 'post') as mock_post: org = OrgService.create_org(TestOrgInfo.org_branch_name, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org_branch_name['name'] mock_post.assert_called() actual_data = mock_post.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': f"{dictionary.get('name')}-{TestOrgInfo.org_branch_name['branchName']}", 'paymentInfo': { 'methodOfPayment': OrgService._get_default_payment_method_for_creditcard(), 'billable': True } } assert expected_data == actual_data
def test_create_basic_org_assert_pay_request_is_correct(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" user = factory_user_model() with patch.object(RestService, 'post') as mock_post: patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org1['name'] mock_post.assert_called() actual_data = mock_post.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name'), 'paymentInfo': { 'methodOfPayment': OrgService._get_default_payment_method_for_creditcard() } } assert expected_data == actual_data
def test_create_product_multiple_subscription(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an Org can be created.""" user_with_token = TestUserInfo.user_bceid_tester user_with_token['keycloak_guid'] = TestJwtClaims.public_bceid_user['sub'] user = factory_user_model(user_with_token) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org1['name'] patch_token_info(TestJwtClaims.public_bceid_user, monkeypatch) subscriptions = ProductService.create_product_subscription( dictionary['id'], TestOrgProductsInfo.org_products2, skip_auth=True) assert next( prod for prod in subscriptions if prod.get('code') == TestOrgProductsInfo.org_products2['subscriptions'][0]['productCode']) assert next( prod for prod in subscriptions if prod.get('code') == TestOrgProductsInfo.org_products2['subscriptions'][1]['productCode'])
def test_get_invitations(session, auth_mock, keycloak_mock): # pylint:disable=unused-argument """Assert that invitations for an org can be retrieved.""" with patch.object(InvitationService, 'send_invitation', return_value=None): user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role[ 'sub'] user = factory_user_model(user_info=user_with_token) org = OrgService.create_org(TestOrgInfo.org1, user.id) org_dictionary = org.as_dict() invitation_info = factory_invitation(org_dictionary['id']) invitation = InvitationService.create_invitation( invitation_info, UserService(user), {}, '') response = InvitationService.get_invitations_for_org( org_dictionary['id'], 'PENDING', TestJwtClaims.public_user_role) assert response assert len(response) == 1 assert response[0].recipient_email == invitation.as_dict( )['recipientEmail']
def test_delete_org_removes_user_from_account_holders_group( session, auth_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an Org deletion removes the user from account holders group.""" # Create a user in keycloak keycloak_service = KeycloakService() request = KeycloakScenario.create_user_request() keycloak_service.add_user(request, return_if_exists=True) kc_user = keycloak_service.get_user_by_username(request.user_name) user = factory_user_model( TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user.id)) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) patch_pay_account_delete(monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) OrgService.delete_org(org.as_dict().get('id')) user_groups = keycloak_service.get_user_groups(user_id=kc_user.id) groups = [] for group in user_groups: groups.append(group.get('name')) assert GROUP_ACCOUNT_HOLDERS not in groups
def test_validate_token_accepted(session, auth_mock, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Validate invalid invitation token.""" with patch.object(InvitationService, 'send_invitation', return_value=None): user = factory_user_model(TestUserInfo.user_test) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) org_dictionary = org.as_dict() user_invitee = factory_user_model(TestUserInfo.user1) invitation_info = factory_invitation(org_dictionary['id']) new_invitation = InvitationService.create_invitation( invitation_info, User(user_invitee), '').as_dict() confirmation_token = InvitationService.generate_confirmation_token( new_invitation['id']) InvitationService.accept_invitation(new_invitation['id'], User(user_invitee), '') with pytest.raises(BusinessException) as exception: InvitationService.validate_token(confirmation_token) assert exception.value.code == Error.ACTIONED_INVITATION.name
def post(): """Post a new org using the request body. If the org already exists, update the attributes. """ token = g.jwt_oidc_token_info request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: user = UserService.find_by_jwt_token(token) if user is None: response, status = {'message': 'Not authorized to perform this action'}, \ http_status.HTTP_401_UNAUTHORIZED return response, status response, status = OrgService.create_org(request_json, user.identifier, token).as_dict(), \ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status
def test_create_basic_org_assert_pay_request_is_correct_online_banking(session, keycloak_mock): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" user = factory_user_model() with patch.object(RestService, 'post') as mock_post: org = OrgService.create_org(TestOrgInfo.org_onlinebanking, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org1['name'] mock_post.assert_called() actual_data = mock_post.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name'), 'paymentInfo': { 'methodOfPayment': PaymentMethod.ONLINE_BANKING.value, 'billable': True } } assert expected_data == actual_data
def test_delete_user_where_org_has_another_owner(session, auth_mock): # pylint:disable=unused-argument """Assert that a user can be deleted.""" # Create a user and org user_model = factory_user_model(user_info=TestUserInfo.user_test) contact = factory_contact_model() contact_link = ContactLinkModel() contact_link.contact = contact contact_link.user = user_model contact_link.commit() org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id) org_dictionary = org.as_dict() org_id = org_dictionary['id'] entity = factory_entity_model(entity_info=TestEntityInfo.entity_lear_mock) affiliation = AffiliationModel(org_id=org_id, entity_id=entity.id) affiliation.save() # Create another user and add membership to the above org user_model2 = factory_user_model(user_info=TestUserInfo.user2) contact = factory_contact_model() contact_link = ContactLinkModel() contact_link.contact = contact contact_link.user = user_model2 contact_link.commit() membership = MembershipModel(org_id=org_id, user_id=user_model2.id, membership_type_code='OWNER', membership_type_status=Status.ACTIVE.value) membership.save() membership.commit() # with pytest.raises(BusinessException) as exception: UserService.delete_user(TestJwtClaims.get_test_user(user_model2.keycloak_guid)) updated_user = UserModel.find_by_jwt_token(TestJwtClaims.get_test_user(user_model2.keycloak_guid)) assert len(updated_user.contacts) == 0 user_orgs = MembershipModel.find_orgs_for_user(updated_user.id) for org in user_orgs: assert org.status_code == 'INACTIVE'
def test_delete_user_is_member_returns_204(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument """Test if the user is the member of a team assert status is 204.""" user_model = factory_user_model(user_info=TestUserInfo.user_test) contact = factory_contact_model() contact_link = ContactLinkModel() contact_link.contact = contact contact_link.user = user_model contact_link.commit() org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id) org_dictionary = org.as_dict() org_id = org_dictionary['id'] entity = factory_entity_model(entity_info=TestEntityInfo.entity_lear_mock) affiliation = AffiliationModel(org_id=org_id, entity_id=entity.id) affiliation.save() user_model2 = factory_user_model(user_info=TestUserInfo.user2) contact = factory_contact_model() contact_link = ContactLinkModel() contact_link.contact = contact contact_link.user = user_model2 contact_link.commit() membership = MembershipModel(org_id=org_id, user_id=user_model2.id, membership_type_code='MEMBER', membership_type_status=Status.ACTIVE.value) membership.save() claims = copy.deepcopy(TestJwtClaims.edit_role.value) claims['sub'] = str(user_model2.keycloak_guid) headers = factory_auth_header(jwt=jwt, claims=claims) rv = client.delete('/api/v1/users/@me', headers=headers, content_type='application/json') assert rv.status_code == http_status.HTTP_204_NO_CONTENT
def test_update_basic_org_assert_pay_request_is_correct(session, keycloak_mock): # pylint:disable=unused-argument """Assert that while org updation , pay-api gets called with proper data for basic accounts.""" user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub'] user = factory_user_model(user_info=user_with_token) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) with patch.object(RestService, 'put') as mock_put: new_payment_method = TestPaymentMethodInfo.get_payment_method_input(PaymentMethod.ONLINE_BANKING) org = OrgService.update_org(org, new_payment_method, token_info=TestJwtClaims.public_user_role) assert org dictionary = org.as_dict() mock_put.assert_called() actual_data = mock_put.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name'), 'paymentInfo': { 'methodOfPayment': PaymentMethod.ONLINE_BANKING.value, 'billable': True } } assert expected_data == actual_data, 'updating to Online Banking works.' new_payment_method = TestPaymentMethodInfo.get_payment_method_input(PaymentMethod.DIRECT_PAY) org = OrgService.update_org(org, new_payment_method, token_info=TestJwtClaims.public_user_role) assert org dictionary = org.as_dict() mock_put.assert_called() actual_data = mock_put.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name'), 'paymentInfo': { 'methodOfPayment': PaymentMethod.DIRECT_PAY.value, 'billable': True } } assert expected_data == actual_data, 'updating bank to Credit Card works.'
def test_reject_org(session, keycloak_mock): # pylint:disable=unused-argument """Assert that an Affidavit can be rejected.""" user = factory_user_model_with_contact() token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.BCEID.value) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(token_info=token_info, affidavit_info=affidavit_info) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id, token_info=token_info) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.PENDING_AFFIDAVIT_REVIEW.value org = OrgService.approve_or_reject(org_dict['id'], is_approved=False, token_info=token_info) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.REJECTED.value affidavit = AffidavitService.find_affidavit_by_org_id(org_dict['id']) assert affidavit['status'] == AffidavitStatus.REJECTED.value
def test_accept_invitation(session, auth_mock, keycloak_mock): # pylint:disable=unused-argument """Accept the invitation and add membership from the invitation to the org.""" with patch.object(InvitationService, 'send_invitation', return_value=None): with patch.object(auth, 'check_auth', return_value=True): with patch.object(InvitationService, 'notify_admin', return_value=None): user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub'] user = factory_user_model(user_with_token) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) org_dictionary = org.as_dict() invitation_info = factory_invitation(org_dictionary['id']) user_with_token_invitee = TestUserInfo.user1 user_with_token_invitee['keycloak_guid'] = TestJwtClaims.edit_role_2['sub'] user_invitee = factory_user_model(user_with_token_invitee) new_invitation = InvitationService.create_invitation(invitation_info, User(user_invitee), {}, '') new_invitation_dict = new_invitation.as_dict() InvitationService.accept_invitation(new_invitation_dict['id'], User(user_invitee), '') members = MembershipService.get_members_for_org(org_dictionary['id'], 'PENDING_APPROVAL', token_info=TestJwtClaims.public_user_role) assert members assert len(members) == 1
def test_delete_org_with_affiliation(session, auth_mock, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an org cannot be deleted.""" user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub'] user = factory_user_model(user_info=user_with_token) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user.id) org_id = org.as_dict()['id'] entity_service = factory_entity_service(entity_info=TestEntityInfo.entity_lear_mock) entity_dictionary = entity_service.as_dict() business_identifier = entity_dictionary['business_identifier'] AffiliationService.create_affiliation(org_id, business_identifier, TestEntityInfo.entity_lear_mock['passCode']) patch_token_info(TestJwtClaims.public_user_role, monkeypatch) patch_pay_account_delete(monkeypatch) OrgService.delete_org(org_id) assert len(AffiliationService.find_visible_affiliations_by_org_id(org_id)) == 0
def test_task_creation(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that affidavit reupload creates new task.""" user = factory_user_model_with_contact() token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.BCEID.value) patch_token_info(token_info, monkeypatch) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(affidavit_info=affidavit_info) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_id = org.as_dict().get('id') task_model: TaskModel = TaskModel.find_by_task_for_account( org_id, TaskStatus.OPEN.value) assert task_model is not None, 'New Open should be generated' task_model.status = TaskStatus.HOLD.value # set current task to hold.Its a staff action new_affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(affidavit_info=new_affidavit_info) assert TaskModel.find_by_id( task_model.id).status == TaskStatus.CLOSED.value assert TaskModel.find_by_task_for_account( org_id, TaskStatus.OPEN.value) is not None
def test_accept_invitation_exceptions(session, auth_mock): # pylint:disable=unused-argument """Accept the invitation and add membership from the invitation to the org.""" with patch.object(InvitationService, 'send_invitation', return_value=None): with patch.object(auth, 'check_auth', return_value=True): with patch.object(InvitationService, 'notify_admin', return_value=None): user = factory_user_model(TestUserInfo.user_test) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) org_dictionary = org.as_dict() invitation_info = factory_invitation(org_dictionary['id']) with pytest.raises(BusinessException) as exception: InvitationService.accept_invitation(None, User(user), '') assert exception.value.code == Error.DATA_NOT_FOUND.name new_invitation = InvitationService.create_invitation( invitation_info, User(user), {}, '') new_invitation_dict = new_invitation.as_dict() InvitationService.accept_invitation(new_invitation_dict['id'], User(user), '') with pytest.raises(BusinessException) as exception: InvitationService.accept_invitation( new_invitation_dict['id'], User(user), '') assert exception.value.code == Error.ACTIONED_INVITATION.name with pytest.raises(BusinessException) as exception: expired_invitation: InvitationModel = InvitationModel \ .find_invitation_by_id(new_invitation_dict['id']) expired_invitation.invitation_status = InvitationStatusModel.get_status_by_code( 'EXPIRED') expired_invitation.save() InvitationService.accept_invitation( expired_invitation.id, User(user), '') assert exception.value.code == Error.EXPIRED_INVITATION.name
def test_reject_org(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an Affidavit can be rejected.""" user = factory_user_model_with_contact( user_info=TestUserInfo.user_bceid_tester) token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.BCEID.value) patch_token_info(token_info, monkeypatch) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() affidavit1 = AffidavitService.create_affidavit( affidavit_info=affidavit_info) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() affidavit = AffidavitService.create_affidavit( affidavit_info=affidavit_info) assert affidavit1.as_dict().get('status', None) == AffidavitStatus.INACTIVE.value assert affidavit.as_dict().get('status', None) == AffidavitStatus.PENDING.value org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.PENDING_STAFF_REVIEW.value task_model = TaskModel.find_by_task_for_account( org_dict['id'], status=TaskStatus.OPEN.value) assert task_model.relationship_id == org_dict['id'] assert task_model.action == TaskAction.AFFIDAVIT_REVIEW.value task_info = { 'status': TaskStatus.OPEN.value, 'relationshipStatus': TaskRelationshipStatus.REJECTED.value, 'remarks': ['Test Remark'] } task = TaskService.update_task(TaskService(task_model), task_info) task_dict = task.as_dict() affidavit = AffidavitService.find_affidavit_by_org_id( task_dict['relationship_id']) assert affidavit['status'] == AffidavitStatus.REJECTED.value
def test_delete_user(session, auth_mock, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that a user can be deleted.""" user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.user_test['sub'] user_model = factory_user_model(user_info=user_with_token) contact = factory_contact_model() contact_link = ContactLinkModel() contact_link.contact = contact contact_link.user = user_model contact_link.commit() patch_token_info(TestJwtClaims.user_test, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id) UserService.delete_user() updated_user = UserModel.find_by_jwt_token() assert len(updated_user.contacts) == 0 user_orgs = MembershipModel.find_orgs_for_user(updated_user.id) for org in user_orgs: assert org.status_code == 'INACTIVE'
def test_get_invitations_by_org_id(session, auth_mock, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Find an existing invitation with the provided org id.""" with patch.object(InvitationService, 'send_invitation', return_value=None): patch_token_info(TestJwtClaims.public_user_role, monkeypatch) user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role[ 'sub'] user = factory_user_model(user_with_token) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) org_dictionary = org.as_dict() org_id = org_dictionary['id'] invitation_info = factory_invitation(org_dictionary['id']) InvitationService.create_invitation(invitation_info, User(user), '').as_dict() invitations: list = InvitationService.get_invitations_for_org( org_id, status='PENDING', token_info=TestJwtClaims.public_user_role) assert invitations assert len(invitations) == 1
def test_delete_org_with_members(session, auth_mock, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an org can be deleted.""" user_with_token = TestUserInfo.user_test user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub'] user = factory_user_model(user_info=user_with_token) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user.id) user2 = factory_user_model(user_info=TestUserInfo.user2) factory_membership_model(user2.id, org._model.id, member_type='COORDINATOR') user3 = factory_user_model(user_info=TestUserInfo.user3) factory_membership_model(user3.id, org._model.id, member_type='ADMIN') patch_token_info(TestJwtClaims.public_user_role, monkeypatch) patch_pay_account_delete(monkeypatch) org_id = org.as_dict()['id'] OrgService.delete_org(org_id) assert len(MembershipService.get_members_for_org(org_id)) == 0
def test_create_product_single_subscription_duplicate_error(session, keycloak_mock): # pylint:disable=unused-argument """Assert that an Org can be created.""" user_with_token = TestUserInfo.user_bceid_tester user_with_token['keycloak_guid'] = TestJwtClaims.public_bceid_user['sub'] user = factory_user_model(user_with_token) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org1['name'] subscriptions = ProductService.create_product_subscription(dictionary['id'], TestOrgProductsInfo.org_products_business, skip_auth=True, token_info=TestJwtClaims.public_bceid_user) assert next(prod for prod in subscriptions if prod.get('code') == TestOrgProductsInfo.org_products_business['subscriptions'][0]['productCode']) with pytest.raises(BusinessException) as exception: ProductService.create_product_subscription(dictionary['id'], TestOrgProductsInfo.org_products_business, skip_auth=True, token_info=TestJwtClaims.public_bceid_user) assert exception.value.code == Error.PRODUCT_SUBSCRIPTION_EXISTS.name
def test_approve_org(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an Affidavit can be approved.""" user = factory_user_model_with_contact() token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.BCEID.value) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(token_info=token_info, affidavit_info=affidavit_info) monkeypatch.setattr('auth_api.utils.user_context._get_token_info', lambda: token_info) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.PENDING_STAFF_REVIEW.value org = OrgService.approve_or_reject(org_dict['id'], is_approved=True, token_info=token_info) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.ACTIVE.value affidavit = AffidavitService.find_affidavit_by_org_id(org_dict['id']) assert affidavit['status'] == AffidavitStatus.APPROVED.value
def test_hold_task(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that a task can be updated.""" user_with_token = TestUserInfo.user_bceid_tester user_with_token['keycloak_guid'] = TestJwtClaims.public_bceid_user['sub'] user = factory_user_model_with_contact(user_with_token) patch_token_info(TestJwtClaims.public_bceid_user, monkeypatch) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(affidavit_info=affidavit_info) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.PENDING_STAFF_REVIEW.value token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.STAFF.value) patch_token_info(token_info, monkeypatch) tasks = TaskService.fetch_tasks(task_status=[TaskStatus.OPEN.value], page=1, limit=10) fetched_tasks = tasks['tasks'] fetched_task = fetched_tasks[0] task_info = { 'relationshipStatus': TaskRelationshipStatus.PENDING_STAFF_REVIEW.value, 'status': TaskStatus.HOLD.value, 'remarks': ['Test Remark'] } task: TaskModel = TaskModel.find_by_task_id(fetched_task['id']) task = TaskService.update_task(TaskService(task), task_info=task_info) dictionary = task.as_dict() assert dictionary['status'] == TaskStatus.HOLD.value assert dictionary[ 'relationship_status'] == TaskRelationshipStatus.PENDING_STAFF_REVIEW.value assert dictionary['remarks'] == ['Test Remark']
def test_create_basic_org_assert_pay_request_is_govm(session, keycloak_mock, staff_user_mock): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" user = factory_user_model() TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.STAFF.value, roles=['create_accounts']) with patch.object(RestService, 'post') as mock_post: org = OrgService.create_org(TestOrgInfo.org_govm, user_id=user.id) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org_govm['name'] mock_post.assert_called() actual_data = mock_post.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name') + '-' + dictionary.get('branch_name'), 'paymentInfo': { 'methodOfPayment': PaymentMethod.EJV.value, 'billable': False } } assert expected_data == actual_data
def test_update_invitation_verify_different_tokens( session, auth_mock, keycloak_mock, # pylint:disable=unused-argument monkeypatch): """Update the specified invitation with new data.""" with patch.object(InvitationService, 'send_invitation', return_value=None): user = factory_user_model(TestUserInfo.user_test) patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) org_dictionary = org.as_dict() invitation_info = factory_invitation(org_dictionary['id']) new_invitation = InvitationService.create_invitation( invitation_info, User(user), '') old_token = new_invitation.as_dict().get('token') with freeze_time( lambda: datetime.now() + timedelta(seconds=1) ): # to give time difference..or else token will be same.. updated_invitation = new_invitation.update_invitation( User(user), '').as_dict() new_token = updated_invitation.get('token') assert old_token != new_token assert updated_invitation['status'] == 'PENDING'
def test_put_basic_org_assert_pay_request_is_govm(session, keycloak_mock, staff_user_mock): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" user = factory_user_model() TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.STAFF.value, roles=['create_accounts']) user2 = factory_user_model(TestUserInfo.user2) public_token_info = TestJwtClaims.get_test_user(sub=user2.keycloak_guid, source=LoginSource.STAFF.value, roles=['gov_account_user']) org: OrgService = OrgService.create_org(TestOrgInfo.org_govm, user_id=user.id) assert org with patch.object(RestService, 'put') as mock_post: payment_details = TestPaymentMethodInfo.get_payment_method_input_with_revenue() org_body = { 'mailingAddress': TestOrgInfo.get_mailing_address(), **payment_details } org = OrgService.update_org(org, org_body, token_info=public_token_info) assert org dictionary = org.as_dict() assert dictionary['name'] == TestOrgInfo.org_govm['name'] mock_post.assert_called() actual_data = mock_post.call_args.kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': dictionary.get('name') + '-' + dictionary.get('branch_name'), 'paymentInfo': { 'methodOfPayment': 'EJV', 'billable': False, 'revenueAccount': payment_details.get('paymentInfo').get('revenueAccount') }, 'contactInfo': TestOrgInfo.get_mailing_address() } assert expected_data == actual_data
def test_create_premium_org_assert_pay_request_is_correct( session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that while org creation , pay-api gets called with proper data for basic accounts.""" bcol_response = Mock(spec=Response) bcol_response.json.return_value = { 'userId': 'PB25020', 'accountNumber': '180670', 'orgName': 'BC ONLINE TECHNICAL TEAM DEVL' } bcol_response.status_code = 200 pay_api_response = Mock(spec=Response) pay_api_response.status_code = 201 with patch.object(RestService, 'post', side_effect=[bcol_response, pay_api_response]) as mock_post: user = factory_user_model() patch_token_info({'sub': user.keycloak_guid}, monkeypatch) org = OrgService.create_org(TestOrgInfo.bcol_linked(), user_id=user.id) assert org dictionary = org.as_dict() mock_post.assert_called() actual_data = mock_post.call_args_list[1].kwargs.get('data') expected_data = { 'accountId': dictionary.get('id'), 'accountName': TestOrgInfo.bcol_linked().get('name'), 'paymentInfo': { 'methodOfPayment': PaymentMethod.BCOL.value, 'billable': True }, 'bcolAccountNumber': dictionary.get('bcol_account_id'), 'bcolUserId': dictionary.get('bcol_user_id'), 'contactInfo': TestOrgInfo.bcol_linked().get('mailingAddress') } assert actual_data == expected_data
def test_remove_member_removes_group_to_the_user(session, monkeypatch): # pylint:disable=unused-argument """Assert that accepting an invite adds group to the user.""" # Create a user in keycloak keycloak_service = KeycloakService() request = KeycloakScenario.create_user_request() keycloak_service.add_user(request, return_if_exists=True) kc_user = keycloak_service.get_user_by_username(request.user_name) user = factory_user_model( TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user.id)) # Patch token info def token_info(): # pylint: disable=unused-argument; mocks of library methods return { 'sub': str(kc_user.id), 'username': '******', 'realm_access': { 'roles': [] } } monkeypatch.setattr( 'auth_api.services.keycloak.KeycloakService._get_token_info', token_info) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) # Create another user request = KeycloakScenario.create_user_request() keycloak_service.add_user(request, return_if_exists=True) kc_user2 = keycloak_service.get_user_by_username(request.user_name) user2 = factory_user_model( TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user2.id)) # Add a membership to the user for the org created factory_membership_model(user2.id, org.as_dict().get('id'), member_type='ADMIN', member_status=4) # Find the membership and update to ACTIVE membership = MembershipService.get_membership_for_org_and_user( org.as_dict().get('id'), user2.id) active_membership_status = MembershipStatusCodeModel.get_membership_status_by_code( Status.ACTIVE.name) updated_fields = {'membership_status': active_membership_status} MembershipService(membership).update_membership( updated_fields=updated_fields, token_info=token_info()) user_groups = keycloak_service.get_user_groups(user_id=kc_user2.id) groups = [] for group in user_groups: groups.append(group.get('name')) assert GROUP_ACCOUNT_HOLDERS in groups # Find the membership and update to INACTIVE active_membership_status = MembershipStatusCodeModel.get_membership_status_by_code( Status.INACTIVE.name) updated_fields = {'membership_status': active_membership_status} MembershipService(membership).update_membership( updated_fields=updated_fields, token_info=token_info()) user_groups = keycloak_service.get_user_groups(user_id=kc_user2.id) groups = [] for group in user_groups: groups.append(group.get('name')) assert GROUP_ACCOUNT_HOLDERS not in groups
def test_put_task_product(client, jwt, session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that the task can be updated.""" # 1. Create User # 4. Create Product subscription # 5. Update the created task and the relationship # Post user, org and product subscription headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.staff_admin_role) user_with_token = TestUserInfo.user_staff_admin user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub'] user = factory_user_model_with_contact(user_with_token) patch_token_info( { 'sub': str(user_with_token['keycloak_guid']), 'username': '******', 'realm_access': { 'roles': ['edit'] } }, monkeypatch) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(affidavit_info=affidavit_info) patch_token_info(TestJwtClaims.public_bceid_user, monkeypatch) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_dict = org.as_dict() product_which_doesnt_need_approval = TestOrgProductsInfo.org_products1 rv_products = client.post( f"/api/v1/orgs/{org_dict.get('id')}/products", data=json.dumps(product_which_doesnt_need_approval), headers=headers, content_type='application/json') assert rv_products.status_code == http_status.HTTP_201_CREATED assert schema_utils.validate(rv_products.json, 'org_product_subscriptions_response')[0] tasks = TaskService.fetch_tasks(task_status=[TaskStatus.OPEN.value], page=1, limit=10) assert len(tasks['tasks']) == 1 product_which_needs_approval = TestOrgProductsInfo.org_products_vs rv_products = client.post(f"/api/v1/orgs/{org_dict.get('id')}/products", data=json.dumps(product_which_needs_approval), headers=headers, content_type='application/json') assert rv_products.status_code == http_status.HTTP_201_CREATED assert schema_utils.validate(rv_products.json, 'org_product_subscriptions_response')[0] tasks = TaskService.fetch_tasks(task_status=[TaskStatus.OPEN.value], page=1, limit=10) fetched_tasks = tasks['tasks'] fetched_task = fetched_tasks[1] assert fetched_task[ 'relationship_type'] == TaskRelationshipType.PRODUCT.value # Assert task name product: ProductCodeModel = ProductCodeModel.find_by_code( product_which_needs_approval['subscriptions'][0].get('productCode')) org_name = org_dict['name'] assert fetched_task['name'] == org_name assert fetched_task['type'] == product.description # Assert the task can be updated and the product status is changed to active update_task_payload = { 'relationshipStatus': ProductSubscriptionStatus.ACTIVE.value } headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.staff_role) rv = client.put('/api/v1/tasks/{}'.format(fetched_task['id']), data=json.dumps(update_task_payload), headers=headers, content_type='application/json') dictionary = json.loads(rv.data) assert rv.status_code == http_status.HTTP_200_OK assert dictionary['status'] == TaskStatus.COMPLETED.value assert dictionary[ 'relationshipStatus'] == TaskRelationshipStatus.ACTIVE.value
def test_remove_member_removes_group_to_the_user(session, monkeypatch): # pylint:disable=unused-argument """Assert that accepting an invite adds group to the user.""" # Create a user in keycloak keycloak_service = KeycloakService() request = KeycloakScenario.create_user_request() keycloak_service.add_user(request, return_if_exists=True) kc_user = keycloak_service.get_user_by_username(request.user_name) user = factory_user_model(TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user.id)) # Patch token info def token_info(): # pylint: disable=unused-argument; mocks of library methods return { 'sub': str(kc_user.id), 'username': '******', 'realm_access': { 'roles': [ 'edit' ] }, 'product_code': ProductCode.BUSINESS.value } monkeypatch.setattr('auth_api.utils.user_context._get_token_info', token_info) org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id) # Create another user request = KeycloakScenario.create_user_request() keycloak_service.add_user(request, return_if_exists=True) kc_user2 = keycloak_service.get_user_by_username(request.user_name) user2 = factory_user_model(TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user2.id)) # Add a membership to the user for the org created factory_membership_model(user2.id, org.as_dict().get('id'), member_type='COORDINATOR', member_status=4) # Add a product to org factory_product_model(org.as_dict().get('id'), product_code=ProductCode.BUSINESS.value) # Find the membership and update to ACTIVE membership = MembershipService.get_membership_for_org_and_user(org.as_dict().get('id'), user2.id) active_membership_status = MembershipStatusCodeModel.get_membership_status_by_code(Status.ACTIVE.name) updated_fields = {'membership_status': active_membership_status} with patch.object(ActivityLogPublisher, 'publish_activity', return_value=None) as mock_alp: MembershipService(membership).update_membership(updated_fields=updated_fields, token_info=token_info()) mock_alp.assert_called_with(Activity(action=ActivityAction.APPROVE_TEAM_MEMBER.value, org_id=ANY, name=ANY, id=ANY, value=ANY)) user_groups = keycloak_service.get_user_groups(user_id=kc_user2.id) groups = [] for group in user_groups: groups.append(group.get('name')) assert GROUP_ACCOUNT_HOLDERS in groups # Deactivate Membership with patch.object(ActivityLogPublisher, 'publish_activity', return_value=None) as mock_alp: MembershipService(membership).deactivate_membership(token_info=token_info()) mock_alp.assert_called_with(Activity(action=ActivityAction.REMOVE_TEAM_MEMBER.value, org_id=ANY, name=ANY, id=ANY, value=ANY)) # ACTIVE active_membership_status = MembershipStatusCodeModel.get_membership_status_by_code(Status.ACTIVE.name) updated_fields = {'membership_status': active_membership_status} MembershipService(membership).update_membership(updated_fields=updated_fields, token_info=token_info()) # Find the membership and update to INACTIVE active_membership_status = MembershipStatusCodeModel.get_membership_status_by_code(Status.INACTIVE.name) updated_fields = {'membership_status': active_membership_status} with patch.object(ActivityLogPublisher, 'publish_activity', return_value=None) as mock_alp: MembershipService(membership).update_membership(updated_fields=updated_fields, token_info=token_info()) mock_alp.assert_called_with(Activity(action=ActivityAction.REMOVE_TEAM_MEMBER.value, org_id=ANY, name=ANY, id=ANY, value=ANY)) user_groups = keycloak_service.get_user_groups(user_id=kc_user2.id) groups = [] for group in user_groups: groups.append(group.get('name')) assert GROUP_ACCOUNT_HOLDERS not in groups MembershipService(membership).deactivate_membership()