def setUp(self): super().setUp() self.project = ProjectFactory.create() self.super_user = UserFactory.create() OrganizationRole.objects.create(user=self.super_user, organization=self.project.organization, admin=False) su_role = Role.objects.get(name='superuser') self.super_user.assign_policies(su_role) self.org_admin = UserFactory.create() OrganizationRole.objects.create(user=self.org_admin, organization=self.project.organization, admin=True) self.project_user_1 = UserFactory.create() OrganizationRole.objects.create(user=self.project_user_1, organization=self.project.organization, admin=False) ProjectRole.objects.create(user=self.project_user_1, project=self.project, role='DC') self.project_user_2 = UserFactory.create() OrganizationRole.objects.create(user=self.project_user_2, organization=self.project.organization, admin=False)
def setUp(self): super().setUp() PolicyFactory.load_policies() load_test_data(get_test_data()) UserFactory.create( username='******', password='******')
def add_test_users(self): users = [] # the first two named users will have superuser access named_users = [ {'username': '******', 'email': '*****@*****.**', 'full_name': 'Ian Ross'}, {'username': '******', 'email': '*****@*****.**', 'full_name': 'Oliver Roick'}] # add user's with names in languages that need to be tested. languages = ['el_GR', 'ja_JP', 'hi_IN', 'hr_HR', 'lt_LT'] named_users.append({ 'full_name': 'עזרא ברש' }) for lang in languages: fake = Factory.create(lang) named_users.append({ 'full_name': fake.name() }) for n in range(20): if n < len(named_users): users.append(UserFactory.create( password='******', email_verified=True, last_login=datetime.now(tz=timezone.utc), is_active=True, **named_users[n] )) else: users.append(UserFactory.create( password='******', is_active=(n < 8), full_name=fake.name(), )) print('\nSuccessfully added test users.') return users
def test_full_list(self): """ It should return all users. """ UserFactory.create_batch(2) response = self.request(user=self.user) assert response.status_code == 200 assert len(response.content) == 3
def test_full_list_with_unautorized_user(self): """ It should 403 "You do not have permission to perform this action." """ UserFactory.create_batch(2) response = self.request() assert response.status_code == 403 assert response.content['detail'] == PermissionDenied.default_detail
def setup_models(self): self.u1 = UserFactory.create() self.u2 = UserFactory.create() self.u3 = UserFactory.create() self.org1 = OrganizationFactory.create(name='A', add_users=[self.u1]) self.org2 = OrganizationFactory.create( name='B', add_users=[self.u1, self.u2] ) self.user = UserFactory.create()
def test_PUT_user_with_unauthorized_user(self): user = UserFactory.create() self.test_user = UserFactory.create() self.project = ProjectFactory.create(add_users=[self.test_user]) response = self.request(method='PUT', user=user) assert response.status_code == 403 assert response.content['detail'] == PermissionDenied.default_detail role = ProjectRole.objects.get(project=self.project, user=self.test_user) assert role.role == 'PU'
def test_filter_active(self): """ It should return only one active user (plus the "setup" user). """ UserFactory.create_from_kwargs([ {'is_active': True}, {'is_active': False} ]) response = self.request(user=self.user, get_data={'is_active': True}) assert response.status_code == 200 assert len(response.content) == 2
def test_post_with_unauthorized_user(self): user = UserFactory.create() user_to_add = UserFactory.create(username='******') response = self.request(method='POST', user=user) assert response.status_code == 302 assert ("You don't have permission to add members to this organization" in response.messages) assert OrganizationRole.objects.filter( organization=self.org, user=user_to_add).exists() is False
def test_ordering(self): UserFactory.create_from_kwargs([ {'username': '******'}, {'username': '******'}, {'username': '******'} ]) response = self.request(user=self.user, get_data={'ordering': 'username'}) assert response.status_code == 200 assert len(response.content) == 4 usernames = [user['username'] for user in response.content] assert(usernames == sorted(usernames))
def test_full_list(self): """ It should return all organizations. """ prj_users = UserFactory.create_batch(2) other_user = UserFactory.create() self.project = ProjectFactory.create(add_users=prj_users) response = self.request(user=self.user) assert response.status_code == 200 assert len(response.content) == 2 assert (other_user.username not in [u['username'] for u in response.content])
def test_update_profile_duplicate_email(self): user1 = UserFactory.create(username='******', full_name='John Lennon') user2 = UserFactory.create(username='******') post_data = { 'username': '******', 'email': user1.email, 'full_name': 'Bill Bloggs', } response = self.request(method='POST', user=user2, post_data=post_data) assert 'Failed to update profile information' in response.messages
def _test_should_allow_create_developer_object(self): url = reverse('developer-list') user = UserFactory() user.save() data = self.fake_developer_data(user=user) resp = self.client.post(url, data) resp_data = get_data_from_resp('developer', resp.content) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) self.assertEqual(resp_data['type'], data['type']) self.assertEqual(resp_data['title'], data['title']) self.assertEqual(resp_data['bio'], data['bio']) self.assertEqual(resp_data['availability'], data['availability'])
def setUp(self): super().setUp() self.user = UserFactory.create() self.org_member = UserFactory.create() self.org = OrganizationFactory.create() self.org_role_user = OrganizationRole.objects.create(organization=self.org, user=self.user) self.org_role_member = OrganizationRole.objects.create(organization=self.org, user=self.org_member) self.prj_1 = ProjectFactory.create(organization=self.org) self.prj_2 = ProjectFactory.create(organization=self.org) self.prj_3 = ProjectFactory.create(organization=self.org) self.prj_4 = ProjectFactory.create(organization=self.org) self.prjs = [self.prj_1, self.prj_2, self.prj_3, self.prj_4]
def test_post_with_authorized_user(self): user = UserFactory.create() user_to_add = UserFactory.create(username='******') assign_policies(user) response = self.request(method='POST', user=user) assert response.status_code == 302 assert ('/organizations/{}/members/{}'.format( self.org.slug, user_to_add.username) in response.location ) assert OrganizationRole.objects.filter( organization=self.org, user=user_to_add).exists() is True
def setup_models(self): clauses = { 'clause': [ clause('allow', ['user.*']), clause('allow', ['user.*'], ['user/*']) ] } policy = Policy.objects.create( name='default', body=json.dumps(clauses)) self.user = UserFactory.create() assign_user_policies(self.user, policy) self.test_user = UserFactory.create(username='******')
def test_search_filter(self): """ It should return only two matching users. """ UserFactory.create_from_kwargs([ {'full_name': 'Match'}, {'username': '******'}, {'username': '******'} ]) response = self.request(user=self.user, get_data={'search': 'match'}) assert response.status_code == 200 assert len(response.content) == 2 assert not any([user['username'] == 'excluded' for user in response.content])
def setup_models(self): clauses = { 'clause': [ clause('allow', ['org.*']), clause('allow', ['org.*', 'org.*.*'], ['organization/*']) ] } policy = Policy.objects.create( name='test-policy', body=json.dumps(clauses)) self.user = UserFactory.create() assign_user_policies(self.user, policy) self.org_user = UserFactory.create() self.org = OrganizationFactory.create(add_users=[self.org_user])
def test_set_roles_for_duplicate_username(self): org = OrganizationFactory.create() user1 = UserFactory.create(email='*****@*****.**') UserFactory.create(email='*****@*****.**') data = {'username': user1.email, 'admin': 'true'} serializer = serializers.OrganizationUserSerializer( data=data, context={'organization': org} ) with pytest.raises(ValidationError): serializer.is_valid(raise_exception=True) assert (_('More than one user found for username or email ' '{email}').format(email='*****@*****.**') in serializer.errors['username'])
def setUp(self): super().setUp() PolicyFactory.load_policies() test_objs = load_test_data(get_test_data()) OrganizationRole.objects.create( organization=test_objs['organizations'][0], user=UserFactory.create( username='******', password='******'), admin=True) UserFactory.create( username='******', email='*****@*****.**', full_name="Han Solo", password='******')
def test_update_with_archived_project(self): self.project.archived = True self.project.save() response = self.request(method='PATCH', user=UserFactory.create()) assert response.status_code == 403 self.resource.refresh_from_db() assert self.resource.name != self.post_data['name']
def test_get_users(self): other_user = UserFactory.create() response = self.request(user=self.user) assert response.status_code == 200 assert len(response.content) == 2 assert (other_user.username not in [u['username'] for u in response.content])
def test_add_user_to_organization_that_does_not_exist(self): new_user = UserFactory.create() response = self.request(method='POST', user=self.user, url_kwargs={'organization': 'some-org'}, post_data={'username': new_user.username}) assert response.status_code == 404 assert response.content['detail'] == "Organization not found."
def test_add_user_with_unauthorized_user(self): new_user = UserFactory.create() response = self.request(method='POST', post_data={'username': new_user.username}) assert response.status_code == 403 assert self.org.users.count() == 2 assert response.content['detail'] == PermissionDenied.default_detail
def setup_models(self): self.user = UserFactory.create() self.org = OrganizationFactory.create() self.prj = ProjectFactory.create(organization=self.org) OrganizationRole.objects.create( organization=self.org, user=self.user, admin=True)
def _test_serialize(self, https=False): form = self._get_form('xls-form') self.url = '/collect/' user = UserFactory.create() request = APIRequestFactory().get(self.url) force_authenticate(request, user=user) if https: request.META['SERVER_PROTOCOL'] = 'HTTPS/1.1' project = ProjectFactory.create() questionnaire = QuestionnaireSerializer( data={'xls_form': form}, context={'project': project} ) assert questionnaire.is_valid(raise_exception=True) is True questionnaire.save() form = Questionnaire.objects.get(filename__contains='xls-form') serializer = serializers.XFormListSerializer( form, context={'request': request}) url_refix = 'https' if https else 'http' assert serializer.data['formID'] == questionnaire.data['id_string'] assert serializer.data['name'] == questionnaire.data['title'] assert serializer.data['version'] == questionnaire.data['version'] assert (serializer.data['downloadUrl'] == url_refix + '://testserver' + reverse('form-download', args=[form.id])) assert serializer.data['hash'] == questionnaire.data['md5_hash']
def test_PUT_with_unauthorized_user(self): user = UserFactory.create() data = {'name': 'Org Name'} response = self.request(method='PUT', post_data=data, user=user) assert response.status_code == 403 self.org.refresh_from_db() assert self.org.name == 'Org'
def test_create_private_record_based_on_org_membership(self): user = UserFactory.create() OrganizationRole.objects.create(organization=self.org, user=user) response = self.request(user=user, method='POST') assert response.status_code == 403 assert PartyRelationship.objects.count() == 0 assert response.content['detail'] == PermissionDenied.default_detail
def setup_models(self): self.project = ProjectFactory.create() self.resources = ResourceFactory.create_batch( 2, content_object=self.project, project=self.project) self.denied = ResourceFactory.create(content_object=self.project, project=self.project) ResourceFactory.create() self.user = UserFactory.create() assign_policies(self.user, add_clauses=[ { 'effect': 'deny', 'object': ['resource/*/*/' + self.denied.id], 'action': ['resource.*'], }, { 'effect': 'deny', 'object': ['resource/*/*/*'], 'action': ['resource.unarchive'], }, ]) self.storage = self.get_storage() self.file = self.get_file( '/resources/tests/files/image.jpg', 'rb') self.file_name = self.storage.save('resources/image.jpg', self.file)
def setup_models(self): clauses = { 'clause': [ { 'effect': 'allow', 'object': ['project/*/*', 'spatial/*/*/*', 'spatial_rel/*/*/*', 'party/*/*/*', 'party_rel/*/*/*', 'tenure_rel/*/*/*'], 'action': ['project.*', 'project.*.*', 'spatial.*', 'spatial_rel.*', 'party.*', 'party_rel.*', 'tenure_rel.*'] } ] } policy = Policy.objects.create( name='basic-test', body=json.dumps(clauses)) self.user = UserFactory.create() self.user.assign_policies(policy) self.prj = ProjectFactory.create(slug='test-project', access='public') self.SR = spatial_factories.SpatialRelationshipFactory self.PR = party_factories.PartyRelationshipFactory self.TR = party_factories.TenureRelationshipFactory
def test_get_with_unauthorized_user(self): user = UserFactory.create() response = self.request(user=user) assert response.status_code == 302 assert ("You don't have permission to remove this location." in response.messages)
def test_get_profile(self): self.user = UserFactory.create() response = self.request(user=self.user) assert response.status_code == 200 assert response.content == self.expected_content
def test_unarchive_with_unauthorized_user(self): with pytest.raises(Http404): self.request(user=UserFactory.create()) self.resource.refresh_from_db() assert self.resource.archived is True
def setUp(self): self.user = UserFactory.create(password='******')
def setUp(self): self.superuser = UserFactory.create(is_superuser=True)
def test_send_update_ping_better(settings): with unittest.mock.patch.object( discourse_sso, "DiscourseSigner" ) as fake_discourse_signer_cls, unittest.mock.patch.object( requests, "post") as fake_send_post: fake_discourse_signer = fake_discourse_signer_cls.return_value fake_discourse_signer.sign.return_value = ("payload", "signature") excluded_group = GroupFactory.create(internal_only=False, internal_name="1-excluded") in_group = GroupFactory.create(internal_only=False, internal_name="2-in") not_in_group = GroupFactory.create(internal_only=False, internal_name="3-not-in") in_internal_group = GroupFactory.create(internal_only=True, internal_name="4-internal-in") not_in_internal_group = GroupFactory.create( internal_only=True, internal_name="5-internal-not-in") del not_in_group, not_in_internal_group # not used; names for documentation user = UserFactory.create( email="*****@*****.**", username="******", full_name="Foo Bar", mc_username="******", gh_username="******", irc_nick="XxXmeepXxX", discord_id="foobar#1234", ) user.groups.set([excluded_group, in_group, in_internal_group]) settings.SSO_ENDPOINTS = TEST_SSO_ENDPOINTS send_update_ping(user, exclude_groups=[excluded_group.id]) django_rq.get_worker().work(burst=True) fake_send_post.assert_called_once_with( "http://discourse.example.com/admin/users/sync_sso", data={ "sso": "payload", "sig": "signature", "api_key": "discourse-api-key", "api_username": "******" }, ) fake_discourse_signer.sign.assert_called_once_with({ "nonce": str(user.id), "email": "*****@*****.**", "require_activation": "false", "external_id": user.id, "username": "******", "name": "Foo Bar", "custom.user_field_1": "meep", "custom.user_field_2": "XxXmeepXxX", "custom.user_field_3": "meeep", "custom.user_field_4": "foobar#1234", "moderator": False, "admin": False, "add_groups": "2-in", "remove_groups": "1-excluded,3-not-in", }) send_update_ping(user) django_rq.get_worker().work(burst=True) fake_discourse_signer.sign.assert_called_with({ "nonce": str(user.id), "email": "*****@*****.**", "require_activation": "false", "external_id": user.id, "username": "******", "name": "Foo Bar", "custom.user_field_1": "meep", "custom.user_field_2": "XxXmeepXxX", "custom.user_field_3": "meeep", "custom.user_field_4": "foobar#1234", "moderator": False, "admin": False, "add_groups": "1-excluded,2-in", "remove_groups": "3-not-in", })
def test_get_with_authorized_user(self): user = UserFactory.create() assign_policies(user) response = self.request(user=user) assert response.status_code == 200 assert response.content == self.expected_content
def test_get_non_existent_location(self): user = UserFactory.create() assign_policies(user) with pytest.raises(Http404): self.request(user=user, url_kwargs={'location': 'abc123'})
def setUp(self): super(ModerateFontTestCase, self).setUp() self.user = UserFactory(is_superuser=True, username='******') self.font_1 = FontFactory(owner=self.user, status=STATUS_ON_REVIEW)
def test_post_with_unauthorized_user(self): response = self.request(method='POST', user=UserFactory.create()) assert ("You don't have permission to add resources." in response.messages) assert self.project.resources.count() == 1 assert self.project.resources.first() == self.attached
def test_get_with_unauthorized_user(self): response = self.request(user=UserFactory.create()) assert response.status_code == 302 assert ("You don't have permission to add resources." in response.messages)
def test_get_with_unauthorized_user(self): response = self.request(user=UserFactory.create()) assert response.status_code == 200 context = self.setup_template_context(resources=[]) context['is_allowed_add_resource'] = False assert response.content == self.render_content(**context)
def setup_models(self): self.users = UserFactory.create_batch(2) self.org = OrganizationFactory.create(add_users=self.users)
def setup_models(self): self.user = UserFactory.create() self.org = OrganizationFactory.create() self.prj = ProjectFactory.create(organization=self.org) self.superuser_role = Role.objects.get(name='superuser')
def setup_models(self): clauses = {'clause': [clause('allow', ['org.create'])]} self.policy = Policy.objects.create(name='allow', body=json.dumps(clauses)) self.user = UserFactory.create() assign_user_policies(self.user, self.policy)
def test_send_update_ping(settings): with unittest.mock.patch.object( discourse_sso, "DiscourseSigner" ) as fake_discourse_signer_cls, unittest.mock.patch.object( requests, "post") as fake_send_post: fake_discourse_signer = fake_discourse_signer_cls.return_value fake_discourse_signer.sign.return_value = ("payload", "signature") user = UserFactory.create( email="*****@*****.**", username="******", full_name="Foo Bar", mc_username="******", gh_username="******", irc_nick="XxXmeepXxX", discord_id="foobar#1234", ) groups = { n: Group(name=n, internal_name=n, internal_only=False) for n in [ "aardvark", "banana", "carrot", "gingerbread", "horseradish", "indigo" ] } Group.objects.bulk_create(groups.values()) user.groups.set(groups[a] for a in ["aardvark", "banana", "carrot"]) user.save() settings.SSO_ENDPOINTS = TEST_SSO_ENDPOINTS send_update_ping(user) django_rq.get_worker().work(burst=True) fake_send_post.assert_called_once_with( "http://discourse.example.com/admin/users/sync_sso", data={ "sso": "payload", "sig": "signature", "api_key": "discourse-api-key", "api_username": "******" }, ) fake_discourse_signer.sign.assert_called_once_with({ "nonce": str(user.id), "email": "*****@*****.**", "require_activation": "false", "external_id": user.id, "username": "******", "name": "Foo Bar", "custom.user_field_1": "meep", "custom.user_field_2": "XxXmeepXxX", "custom.user_field_3": "meeep", "custom.user_field_4": "foobar#1234", "moderator": False, "admin": False, "add_groups": "aardvark,banana,carrot", "remove_groups": "gingerbread,horseradish,indigo", })
def test_get_with_unauthorized_user(self): user = UserFactory.create() response = self.request(user=user) assert response.status_code == 302 assert ("You don't have permission to add tenure relationships to " "this project." in response.messages)
def setup_models(self): self.user = UserFactory.create() self.org = OrganizationFactory.create() self.prj = ProjectFactory.create(organization=self.org) self.prj_2 = ProjectFactory.create(organization=self.org) self.prj_3 = ProjectFactory.create(organization=self.org) OrganizationRole.objects.create( organization=self.org, user=self.user, admin=True) QuestionnaireFactory.create( project=self.prj, xls_form=get_form('test_standard_questionnaire'), filename='test_standard_questionnaire', id_string='test_standard_questionnaire', version=20160727122110) questionnaire = QuestionnaireFactory.create( project=self.prj_2, xls_form=get_form('test_standard_questionnaire_2'), filename='test_standard_questionnaire_2', id_string='test_standard_questionnaire_2', version=20160727122111) QuestionFactory.create( name='location_geometry', label='Location of Parcel', type='GS', questionnaire=questionnaire) QuestionnaireFactory.create( project=self.prj_3, xls_form=get_form('test_standard_questionnaire_bad'), filename='test_standard_questionnaire_bad', id_string='test_standard_questionnaire_bad', version=20160727122112) # project 1 create_attrs_schema( project=self.prj, dict=default_party_xform_group, content_type=ContentType.objects.get( app_label='party', model='party'), errors=[]) create_attrs_schema( project=self.prj, dict=individual_party_xform_group, content_type=ContentType.objects.get( app_label='party', model='party'), errors=[]) create_attrs_schema( project=self.prj, dict=location_xform_group, content_type=ContentType.objects.get( app_label='spatial', model='spatialunit'), errors=[]) create_attrs_schema( project=self.prj, dict=tenure_relationship_xform_group, content_type=ContentType.objects.get( app_label='party', model='tenurerelationship'), errors=[]) # project 2 create_attrs_schema( project=self.prj_2, dict=default_party_xform_group, content_type=ContentType.objects.get( app_label='party', model='party'), errors=[]) create_attrs_schema( project=self.prj_2, dict=individual_party_xform_group, content_type=ContentType.objects.get( app_label='party', model='party'), errors=[]) create_attrs_schema( project=self.prj_2, dict=location_xform_group, content_type=ContentType.objects.get( app_label='spatial', model='spatialunit'), errors=[]) create_attrs_schema( project=self.prj_2, dict=tenure_relationship_xform_group, content_type=ContentType.objects.get( app_label='party', model='tenurerelationship'), errors=[])
def test_get_with_unauthorized_user(self): user = UserFactory.create() response = self.request(user=user) assert response.status_code == 200 expected = self.render_content(is_allowed_add_location=False) assert response.content == expected
def test_escrow_amount_equals_zero(self): user = UserFactory() amount = get_user_balance(user.id) self.assertEqual(amount, Decimal(0))
def setup_models(self): clauses = {'clause': [clause('allow', ['user.list'])]} policy = Policy.objects.create(name='test-default', body=json.dumps(clauses)) self.user = UserFactory.create() assign_user_policies(self.user, policy)
def test_get_with_superuser(self): superuser = UserFactory.create(is_superuser=True) response = self.request(user=superuser) assert response.status_code == 200 assert response.content == self.render_content(user=superuser, is_superuser=True)
def setUp(self): self.user = UserFactory.create(first_name='test123', password='******')
def setup_models(self): self.member = UserFactory.create() self.user = UserFactory.create() self.org = OrganizationFactory.create( add_users=[self.member, self.user])
def test_should_return_user_balance(self): user = UserFactory() self.client.force_authenticate(user=user) response = self.client.get( reverse('user-balance-detail', args=('me', ))) self.assertEqual(response.status_code, status.HTTP_200_OK)
def setup_models(self): self.user = UserFactory.create() self.member = UserFactory.create() self.org = OrganizationFactory.create(add_users=[self.member]) self.prj = ProjectFactory.create(organization=self.org)
def setup_models(self): self.user = UserFactory.create() self.project = ProjectFactory.create() self.resource = ResourceFactory.create(content_object=self.project, project=self.project) assign_permissions(self.user)
def test_get_with_unauthorized_user(self): user = UserFactory.create() response = self.request(user=user) assert response.status_code == 302 assert ("You don't have permission to add members to this organization" in response.messages)
def setup_models(self): self.project = ProjectFactory.create() self.user = UserFactory.create() assign_permissions(self.user)
def test_get_from_non_existent_project(self): user = UserFactory.create() assign_policies(user) with pytest.raises(Http404): self.request(user=user, url_kwargs={'project': 'abc123'})