Exemple #1
0
 def setUp(self):
     self.from_profile = ProfileFactory.create()
     self.to_profile = ProfileFactory.create()
     self.other_profile = ProfileFactory.create()
     self.from_profile.friends.add(self.to_profile)
     self.from_profile.friends.add(self.other_profile)
     self.proposal = PairProposal.objects.create(
         from_profile=self.from_profile, to_profile=self.to_profile)
Exemple #2
0
 def test_delete(self):
     profile = ProfileFactory()
     profile.partner_staff_member = profile.user.pk
     profile.save()
     models.delete_partner_relationship(None, profile.user)
     profile_updated = models.UserProfile.objects.get(pk=profile.pk)
     self.assertIsNone(profile_updated.partner_staff_member)
     user = models.User.objects.get(pk=profile.user.pk)
     self.assertFalse(user.is_active)
Exemple #3
0
 def test_has_proposed_to_friend(self):
     profile = ProfileFactory.create(state=self.swing_state.name)
     friend = ProfileFactory.create(state=self.safe_state.name)
     profile.friends.add(friend)
     ctx = ProfileContext(profile)
     self.assertFalse(ctx.has_proposed_to_friend(friend))
     PairProposal.objects.create(
         from_profile=profile, to_profile=friend)
     ctx = ProfileContext(profile)
     self.assertTrue(ctx.has_proposed_to_friend(friend))
Exemple #4
0
 def test_random(self):
     profile = ProfileFactory.create(allow_random=True)
     rando = ProfileFactory.create(allow_random=True)
     form = PairProposalForm(profile, data={'to_profile': rando.id})
     self.assertTrue(form.is_valid())
     form.save()
     self.proposal = profile.proposals_made.get()
     form = RejectPairProposalForm(data=self._data(),
                                   instance=self.proposal)
     self.assertTrue(form.is_valid())
     form.save()
Exemple #5
0
 def test_valid(self):
     profile = ProfileFactory.create()
     friend = ProfileFactory.create()
     profile.friends.add(friend)
     form = PairProposalForm(profile, data={'to_profile': friend.id})
     self.assertEqual(len(PairProposal.objects.all()), 0)
     self.assertTrue(form.is_valid())
     form.save()
     self.assertEqual(len(PairProposal.objects.all()), 1)
     proposal = PairProposal.objects.get()
     self.assertEqual(proposal.from_profile, profile)
     self.assertEqual(proposal.to_profile, friend)
Exemple #6
0
 def test_no_paired_friends(self):
     profile = ProfileFactory.create()
     friend = ProfileFactory.create()
     profile.friends.add(friend)
     paired_friend = ProfileFactory.create()
     paired_friend.paired_with = ProfileFactory.create()
     profile.friends.add(paired_friend)
     form = PairProposalForm(profile, data={'to_profile': friend.id})
     self.assertEqual(form.fields['from_profile'].queryset.get(), profile)
     self.assertEqual(set(form.fields['to_profile'].queryset),
                      set(Profile.objects.filter(id=friend.id)))
     self.assertTrue(form.is_valid())
Exemple #7
0
    def test_querydict(self):
        ProfileFactory.create()
        profile = ProfileFactory.create()
        friends = [ProfileFactory.create() for x in range(2)]
        profile.friends.add(*friends)

        form = PairProposalForm(
            profile,
            data=QueryDict('from_profile=%s&to_profile=%s' %
                           (profile.id, friends[0].id)))
        self.assertEqual(form.fields['from_profile'].queryset.get(), profile)
        self.assertEqual(set(form.fields['to_profile'].queryset.all()),
                         set(friends))
Exemple #8
0
    def test_friends_queryset(self):
        ProfileFactory.create()
        profile = ProfileFactory.create()
        friends = [ProfileFactory.create() for x in range(2)]
        profile.friends.add(*friends)

        form = PairProposalForm(profile, data={'to_profile': friends[0].id})
        self.assertEqual(form.fields['from_profile'].queryset.get(), profile)
        self.assertEqual(
            set(form.fields['to_profile'].queryset),
            set(
                Profile.objects.filter(
                    id__in=[friend.id for friend in friends])))
        self.assertTrue(form.is_valid())
    def test_birth_date_validation(self):
        profile = ProfileFactory()

        assert profile.full_clean() is None

        profile.birth_date = timezone.now().date() + timezone.timedelta(days=2)
        with pytest.raises(ValidationError):
            profile.full_clean()

        profile.birth_date = timezone.datetime(199, 1, 1).date()
        with pytest.raises(ValidationError):
            profile.full_clean()
Exemple #10
0
 def test_custom_update_user_is_staff_no_group(self):
     profile = ProfileFactory()
     self.assertFalse(profile.user.is_staff)
     res = models.UserProfile.custom_update_user(profile.user, {}, None)
     self.assertTrue(res)
     profile_updated = models.UserProfile.objects.get(pk=profile.pk)
     self.assertTrue(profile_updated.user.is_staff)
Exemple #11
0
 def test_existing_profile(self, mock_request):
     # This flow shouldn't happen, but in case it does, just merge the
     # profiles
     self.assertEqual(len(Profile.objects.all()), 0)
     request = self.request.get(reverse(confirm_signup))
     request.user = UserFactory()
     ProfileFactory.create(fb_id=request.user.social_auth.get().uid)
     self.assertEqual(len(Profile.objects.all()), 2)
     request.session = self.session
     response = confirm_signup(request)
     # And a new profile will be created from the response, but the existing
     # profile got deleted, so the total number hasn't changed
     self.assertEqual(len(Profile.objects.all()), 2)
     self.assertEqual(response.status_code, HTTP_REDIRECT)
     self.assertTrue(response.has_header('Location'))
     self.assertEqual(response.get('Location'), reverse('users:profile'))
Exemple #12
0
def test_create_application_raises_exception_if_apartment_data_does_not_exist(
):
    data = create_validated_application_data(ProfileFactory(),
                                             ApplicationType.HASO)
    data["apartments"] = [{"priority": 1, "identifier": "this-does-not-exist"}]
    with pytest.raises(InvalidElasticDataError):
        create_application(data)
    def test_name_methods(self):
        profile = ProfileFactory()
        user = profile.user

        assert profile.first_name == user.first_name
        assert profile.last_name == user.last_name
        assert profile.full_name == user.get_full_name()
    def test_to_representation(self):
        profile = ProfileFactory()

        data = ProfileSerializer(profile).data

        assert data["username"] == profile.user.username
        assert data["last_name"] == profile.user.last_name
        assert data["first_name"] == profile.user.first_name
        assert data["description"] == profile.description
Exemple #15
0
def test_application_post(api_client):
    profile = ProfileFactory()
    api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {_create_token(profile)}")
    data = create_application_data(profile)
    response = api_client.post(
        reverse("application_form:application-list"), data, format="json"
    )
    assert response.status_code == 201
    assert response.data == {"application_uuid": data["application_uuid"]}
Exemple #16
0
def test_application_post_writes_audit_log_if_not_authenticated(api_client, caplog):
    data = create_application_data(ProfileFactory())
    api_client.post(reverse("application_form:application-list"), data, format="json")
    audit_event = get_audit_log_event(caplog)
    assert audit_event is not None, "no audit log entry was written"
    assert audit_event["actor"] == {"role": "ANONYMOUS", "profile_id": None}
    assert audit_event["operation"] == "CREATE"
    assert audit_event["target"] == {"id": None, "type": "Application"}
    assert audit_event["status"] == "FORBIDDEN"
Exemple #17
0
 def test_random(self):
     profile = ProfileFactory.create(allow_random=True)
     friend = ProfileFactory.create()
     profile.friends.add(friend)
     # Add a friend and make sure it's there
     self.assertEqual(friend, profile.all_unpaired_friends.get())
     rando = ProfileFactory.create(allow_random=True)
     # The rando also accepts random friends, so it should show up as an
     # unpaired friend
     self.assertEqual(set([friend, rando]),
                      set(profile.all_unpaired_friends))
     form = PairProposalForm(profile, data={'to_profile': rando.id})
     self.assertEqual(len(PairProposal.objects.all()), 0)
     self.assertTrue(form.is_valid())
     form.save()
     self.assertEqual(len(PairProposal.objects.all()), 1)
     proposal = PairProposal.objects.get()
     self.assertEqual(proposal.from_profile, profile)
     self.assertEqual(proposal.to_profile, rando)
 def test_invalid_proposal_id(self):
     """Giving a proposal for a different user gives an error"""
     new_profile = ProfileFactory.create()
     other_proposal = PairProposal.objects.create(
         from_profile=self.other_profile, to_profile=new_profile)
     request = self.request.post(reverse('users:confirm_swap',
                                         args=[other_proposal.ref_id]),
                                 data={})
     request.user = self.to_profile.user
     response = confirm_swap(request, other_proposal.ref_id)
     self.assertContains(response, 'Invalid swap proposal')
Exemple #19
0
 def test_friends_of_friends(self):
     profile = ProfileFactory.create()
     # Start with no friends
     self.assertQuerysetEqual(profile.friends.all(),
                              profile.all_unpaired_friends)
     friend = ProfileFactory.create()
     profile.friends.add(friend)
     # Add a friend and make sure it's there
     self.assertEqual(friend, profile.all_unpaired_friends.get())
     foaf = ProfileFactory.create()
     # After creating another profile, it isn't yet a friend
     self.assertEqual(friend, profile.all_unpaired_friends.get())
     friend.friends.add(foaf)
     # But after adding it as a friend of my friend, I can see it
     self.assertEqual(set([friend, foaf]),
                      set(profile.all_unpaired_friends))
     # But won't see friends-of-friends-of-friends
     foaf.friends.add(ProfileFactory.create())
     self.assertEqual(set([friend, foaf]),
                      set(profile.all_unpaired_friends))
Exemple #20
0
 def test_save_update_name_user_and_profile_unlinked(self):
     fb_id = 1234
     user = UserFactory.create(profile=None, social_auth__uid=fb_id)
     profile = ProfileFactory.create(fb_id=fb_id)
     data = self._data()
     form = LandingPageForm(data=data)
     self.assertTrue(form.is_valid())
     form.save(user)
     user = get_user_model().objects.get(id=user.id)
     self.assertNotEqual(user.get_full_name(), user.profile.fb_name)
     self.assertEqual(user.profile, profile)
Exemple #21
0
 def test_save_model_supervisor(self):
     """If supervisor provided, then set supervisor"""
     mock_form = Mock()
     mock_form.data = {"supervisor": self.superuser.pk}
     obj = ProfileFactory()
     self.assertIsNone(obj.supervisor)
     self.admin.save_model(
         self.request,
         obj,
         mock_form,
         None)
     profile_updated = UserProfile.objects.get(pk=obj.pk)
     self.assertEqual(profile_updated.supervisor, self.superuser)
Exemple #22
0
 def test_save_model_oic(self):
     """If OIC provided, then set OIC"""
     mock_form = Mock()
     mock_form.data = {"oic": self.superuser.pk}
     obj = ProfileFactory()
     self.assertIsNone(obj.oic)
     self.admin.save_model(
         self.request,
         obj,
         mock_form,
         None)
     profile_updated = UserProfile.objects.get(pk=obj.pk)
     self.assertEqual(profile_updated.oic, self.superuser)
    def test_username_uniqueness_validation(self):
        user = UserFactory()
        profile = ProfileFactory(user=user)

        new_user_data = UserFactory()

        data = {"username": new_user_data.username}

        serializer = ProfileSerializer(instance=profile,
                                       data=data,
                                       partial=True)
        assert not serializer.is_valid()
        assert "username" in serializer.errors
Exemple #24
0
 def setUp(self):
     super(_TestSafeStateFriendsOfFriendsMatchBase, self).setUp()
     candidate = CANDIDATE_CLINTON
     self.state_safe = StateFactory.create(
         safe_for=candidate,
         safe_rank=1
     )
     self.user = UserFactory.create(
         profile__state=self.state_safe.name,
         profile__preferred_candidate=candidate)
     tipping_point_rank = 1
     self.foaf_expected_matches = []
     # Create friends that haven't specified a vote choice just for links
     for i in range(2):
         friend_profile = ProfileFactory.create(state='')
         self.user.profile.friends.add(friend_profile)
         # And create friends of these friends in swing states
         for i in range(2):
             state = StateFactory.create(
                 tipping_point_rank=tipping_point_rank)
             foaf = UserFactory.create(
                 profile__state=state.name,
                 profile__preferred_candidate=CANDIDATE_STEIN)
             tipping_point_rank += 1
             friend_profile.friends.add(foaf.profile)
             self.foaf_expected_matches.append(foaf.profile)
     # And make another foaf that's friends with both of my friends
     state = StateFactory.create(
         tipping_point_rank=tipping_point_rank)
     self.foafoaf = UserFactory.create(
         profile__state=state.name,
         profile__preferred_candidate=CANDIDATE_JOHNSON)
     for friend in self.user.profile.friends.all():
         friend.friends.add(self.foafoaf.profile)
     self.foaf_expected_matches.append(self.foafoaf.profile)
     tipping_point_rank += 1
     self.direct_expected_matches = []
     # Create friends in swing states
     for i in range(2):
         state = StateFactory.create(
             tipping_point_rank=tipping_point_rank)
         friend = UserFactory.create(
             profile__state=state.name,
             profile__preferred_candidate=CANDIDATE_JOHNSON)
         tipping_point_rank += 1
         self.user.profile.friends.add(friend.profile)
         self.direct_expected_matches.append(friend.profile)
     # Direct friends are always preferred, so prepend them to expected
     self.expected_matches = (
         self.direct_expected_matches + self.foaf_expected_matches)
 def setUp(self):
     super(TestConfirmSwapView, self).setUp()
     self.request = RequestFactory()
     from_state = StateFactory.create(tipping_point_rank=1)
     self.from_profile = UserFactory.create(
         profile__state=from_state.name).profile
     to_state = StateFactory.create(safe_rank=1)
     self.to_profile = UserFactory.create(
         profile__state=to_state.name).profile
     self.other_profile = ProfileFactory.create()
     self.from_profile.friends.add(self.to_profile)
     self.from_profile.friends.add(self.other_profile)
     self.proposal = PairProposal.objects.create(
         from_profile=self.from_profile, to_profile=self.to_profile)
Exemple #26
0
def test_application_post_writes_audit_log(api_client, caplog):
    profile = ProfileFactory()
    api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {_create_token(profile)}")
    data = create_application_data(profile)
    api_client.post(reverse("application_form:application-list"), data, format="json")
    audit_event = get_audit_log_event(caplog)
    assert audit_event is not None, "no audit log entry was written"
    assert audit_event["actor"] == {"role": "USER", "profile_id": str(profile.pk)}
    assert audit_event["operation"] == "CREATE"
    assert audit_event["target"] == {
        "id": data["application_uuid"],
        "type": "Application",
    }
    assert audit_event["status"] == "SUCCESS"
    def test_partial_update(self):
        user = UserFactory()
        profile = ProfileFactory(user=user)

        new_profile_data = ProfileFactory.build()
        new_user_data = UserFactory.build()

        data = {
            "description": new_profile_data.description,
            "last_name": new_user_data.last_name,
        }

        serializer = ProfileSerializer(instance=profile,
                                       data=data,
                                       partial=True)
        assert serializer.is_valid(), serializer.errors
        serializer.save()

        user.refresh_from_db()
        assert user.last_name == data["last_name"]

        profile.refresh_from_db()
        assert profile.description == data["description"]
Exemple #28
0
 def test_clean_duplicate_email(self):
     """Duplicate email not allowed if user associated as staff member"""
     profile = ProfileFactory(
         partner_staff_member=10,
     )
     self.data["email"] = profile.user.email
     form = forms.PartnerStaffMemberForm(self.data)
     self.assertFalse(form.is_valid())
     self.assertIn(
         "This user already exists under a different partnership: {}".format(
             profile.user.email
         ),
         form.errors["__all__"]
     )
Exemple #29
0
 def test_profile_reason_emoji(self):
     reason = u"💩"
     reasonb64 = base64.b64encode(reason.encode('utf-8'))
     profile = ProfileFactory.create()
     profile.reason = reason
     profile.clean()
     profile.save()
     self.assertEqual(profile.reason, reasonb64)
     self.assertEqual(profile.reason_decoded, reason)
     profile = Profile.objects.get(id=profile.id)
     profile.clean()
     profile.save()
     self.assertEqual(profile.reason, reasonb64)
     self.assertEqual(profile.reason_decoded, reason)
    def test_update(self):
        user = UserFactory()
        profile = ProfileFactory(user=user)

        new_profile_data = ProfileFactory.build()
        new_user_data = UserFactory.build()

        data = {
            "birth_date": new_profile_data.birth_date,
            "description": new_profile_data.description,
            "first_name": new_user_data.first_name,
            "last_name": new_user_data.last_name,
            "username": new_user_data.username,
        }

        serializer = ProfileSerializer(instance=profile, data=data)
        assert serializer.is_valid(), serializer.errors
        profile = serializer.save()

        assert profile.description == data["description"]
        assert profile.birth_date == data["birth_date"]
        assert profile.user.last_name == data["last_name"]
        assert profile.user.first_name == data["first_name"]
        assert profile.user.username == data["username"]