Ejemplo n.º 1
0
    def test_books_list_logged(self):
        user1 = UserFactory.create()
        user2 = UserFactory.create()

        book1 = BookFactory.create(owner=user1)
        book2 = BookFactory.create(owner=user1)
        book3 = BookFactory.create(owner=user2)

        with self.login(user1):
            response = self.client.get('/books/my/')

            self.assertEqual(response.status_code, 200)
            self.assertContains(response, book1.title)
            self.assertContains(response, book2.title)
            self.assertNotContains(response, book3.title)
Ejemplo n.º 2
0
 def test_landlord_name_address_email_creates_details(self, graphql_client):
     graphql_client.request.user = UserFactory()
     ld_1 = EXAMPLE_LANDLORD_DETAILS_INPUT
     result = execute_ld_mutation(graphql_client, **ld_1)
     assert result["errors"] == []
     assert result["isUndeliverable"] is None
     assert result["session"]["landlordDetails"] == ld_1
Ejemplo n.º 3
0
    def test_it_syncs_contacts_that_map_to_existing_users(self):
        user = UserFactory()
        contact = make_contact(user.phone_number, [make_group()])
        self.get_contact_batches.return_value = [[contact]]

        def call_and_ensure_expected_models():
            assert SYNCING_USER_SENTINEL in call()
            ucgs = list(UserContactGroup.objects.all())
            assert str(ucgs) == (
                "[<UserContactGroup: User boop's association with RapidPro "
                "contact group 'Funky Group'>]")
            assert str(
                ucgs[0].earliest_known_date) == '2018-01-02 03:04:05+00:00'

            cgs = list(ContactGroup.objects.all())
            assert str(cgs) == '[<ContactGroup: Funky Group>]'
            assert cgs[0].uuid == 'funky'

        call_and_ensure_expected_models()

        # Now re-sync and ensure idempotency.
        contact.modified_on = make_aware(datetime(2019, 1, 2))
        call_and_ensure_expected_models()

        # Now remove the user's association with the group and make sure it syncs.
        contact.groups[:] = []
        call()
        assert UserContactGroup.objects.count() == 0
Ejemplo n.º 4
0
 def test_materials_listed(self):
     materials = MaterialFactory.create_batch(5)
     self.client.force_login(UserFactory())
     response = self.client.get(reverse("catalog:catalog"))
     self.assertTemplateUsed(response, "catalog/material_list.html")
     for material in materials:
         self.assertContainsMaterialOnce(response, material)
Ejemplo n.º 5
0
def set_up_many(num_instances):
    """Set up many instances."""
    users = UserFactory.create_batch(num_instances)
    artists = ArtistFactory.create_batch(num_instances)
    festivals = FestivalFactory.create_batch(num_instances, artists=artists)
    ranking_sets = []
    rankings = []
    reviews = []
    genres = []
    for user in users:
        for festival in festivals:
            ranking_set = RankingSetFactory.create(festival=festival, user=user)
            ranking_sets.append(ranking_set)
            for artist in artists:
                ranking = RankingFactory.create(ranking_set=ranking_set, artist=artist)
                rankings.append(ranking)

                review = ReviewFactory.create(user=user, artist=artist, festival=festival)
                reviews.append(review)

                genre = GenreFactory.create(review=review)
                genres.append(genre)
    return {'users': users,
            'artists': artists,
            'festivals': festivals,
            'ranking_sets': ranking_sets,
            'rankings': rankings,
            'reviews': reviews,
            'genres': genres}
Ejemplo n.º 6
0
def test_csv_is_inaccessible_to_non_staff_users(client, db):
    user = UserFactory()
    client.force_login(user)

    res = client.get("/admin/download-data/userstats.csv")
    assert res.status_code == 302
    assert res.url == f"/admin/login/?next=/admin/download-data/userstats.csv"
Ejemplo n.º 7
0
 def setUp(self):
     user = UserFactory.create(username="******")
     a = ActivityFactory(user=user)
     t = ActivityTrackFactory.create(activity=a)
     ActivityTrackpointFactory.create(track=t)
     t.reset_trim()
     self.client.login(username='******', password='******')
Ejemplo n.º 8
0
    def test_clean_username(self):
        # A user with proto_user params does not exist yet.
        proto_user = UserFactory.build()

        form = UserCreationForm({
            "username": proto_user.username,
            "password1": proto_user._password,  # pylint: disable=protected-access
            "password2": proto_user._password,  # pylint: disable=protected-access
        })

        assert form.is_valid()
        assert form.clean_username() == proto_user.username

        # Creating a user.
        form.save()

        # The user with proto_user params already exists,
        # hence cannot be created.
        form = UserCreationForm({
            "username": proto_user.username,
            "password1": proto_user._password,
            "password2": proto_user._password,
        })

        assert not form.is_valid()
        assert len(form.errors) == 1
        assert "username" in form.errors
Ejemplo n.º 9
0
 def test_get(self):
     self.user = UserFactory()
     response = self.forced_auth_req("get",
                                     reverse("user-api-profile"),
                                     user=self.user)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data["id"], self.user.pk)
Ejemplo n.º 10
0
def test_admin_envelopes_pdf_works(outreach_client):
    user = create_user_with_all_info()
    bare_user = UserFactory(phone_number='6141234567', username='******')
    res = outreach_client.get(f'{reverse("loc_envelopes")}?user_ids={user.pk},{bare_user.pk},zz')
    assert res.status_code == 200
    assert res['Content-Type'] == 'application/pdf'
    assert res.context['users'] == [user]
Ejemplo n.º 11
0
 def test_join_and_confirm_passenger(self):
     user = UserFactory()
     journey = self._make_journey()
     self.assertIsInstance(journey.join_passenger(user), Passenger)
     journey.confirm_passenger(user)
     self.assertTrue(journey.is_passenger(user))
     self.assertEquals(journey.count_passengers(), 1)
Ejemplo n.º 12
0
def test_legacy_full_name_mutation_updates_user_if_logged_in(
        graphql_client, db):
    user = UserFactory()
    graphql_client.request.user = user
    output = graphql_client.execute("""
        mutation {
          output: norentFullName(input: {
            firstName: "snorri",
            lastName: "heb"
        }) {
            errors { field, messages }
            session {
              firstName,
              lastName,
              onboardingScaffolding { email }
            }
          }
        }
        """)["data"]["output"]
    assert output["errors"] == []
    assert output["session"] == {
        "firstName": "snorri",
        "lastName": "heb",
        "onboardingScaffolding": None,
    }
Ejemplo n.º 13
0
 def test_delete_exception(self):
     """Exceptions are silently ignored, no changes saved"""
     user = UserFactory()
     self.assertTrue(user.is_active)
     self.assertIsNone(models.delete_partner_relationship(None, user))
     user_updated = models.User.objects.get(pk=user.pk)
     self.assertTrue(user_updated.is_active)
Ejemplo n.º 14
0
 def test_landlord_name_address_email_requires_fields(self, graphql_client):
     graphql_client.request.user = UserFactory()
     errors = execute_ld_mutation(graphql_client)["errors"]
     expected_errors = 5
     assert len(errors) == expected_errors
     for i in range(expected_errors):
         assert errors[0]["messages"] == ["This field is required."]
Ejemplo n.º 15
0
def test_logout_works(graphql_client):
    user = UserFactory()
    graphql_client.request.user = user
    logout_mutation = get_frontend_query('LogoutMutation.graphql')
    result = graphql_client.execute(logout_mutation, variables={'input': {}})
    assert len(result['data']['output']['session']['csrfToken']) > 0
    assert graphql_client.request.user.pk is None
Ejemplo n.º 16
0
 def test_leave_passenger(self):
     user = UserFactory()
     journey = self._make_journey()
     journey.join_passenger(user)
     journey.confirm_passenger(user)
     journey.leave_passenger(user)
     self.assertFalse(journey.is_passenger(user))
Ejemplo n.º 17
0
 def test_it_sends_sms_on_success(self):
     UserFactory(phone_number='5551234567')
     assert self.mutate_password_reset() == []
     assert len(self.smsoutbox) == 1
     msg = self.smsoutbox[0]
     assert msg.to == '+15551234567'
     assert 'Your verification code is 123456' in msg.body
Ejemplo n.º 18
0
 def test_destination(self):
     user = UserFactory()
     origin = ResidenceFactory(user=user)
     destination = CampusFactory()
     template = JourneyTemplateFactory(user=user, residence=origin, campus=destination, kind=GOING)
     journey = JourneyFactory(template=template)
     self.assertEquals(journey.destination, destination)
Ejemplo n.º 19
0
 def test_it_works(self, settings):
     configure_airtable_settings(settings)
     user = UserFactory()
     with patch('airtable.sync.Airtable'):
         with patch.object(logger, 'exception') as m:
             sync_user(user)
     m.assert_not_called()
Ejemplo n.º 20
0
 def test_smart_create(self):
     user = UserFactory(
         default_address="bar",
         default_position=Point(882532.74, 545437.43, srid=DEFAULT_PROJECTED_SRID)
     )
     residence = Residence.objects.smart_create(user)
     self.assertIsInstance(residence, Residence)
Ejemplo n.º 21
0
class TestCommentsViewSet(APITestCase):
    """Tests all CommentsViewSet functionality"""
    def setUp(self) -> None:
        self.user = UserFactory()
        token = Token.objects.get(user=self.user)
        self.client.credentials(HTTP_AUTHORIZATION=f'Token {token.key}')
        self.topic = TopicFactory(author=self.user)
        self.post = PostFactory(author=self.user, topic=self.topic)
        self.comment1 = CommentFactory(author=self.user, post=self.post)

    def test_get_comments_by_post(self):
        """Get all comments of particular post"""

        CommentFactory(author=self.user, body='Test comment 2', post=self.post)
        data = {
            'post': self.post.id,
        }
        response = self.client.get(reverse('api:comments-list'), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data.get('results')), 2)

    def test_delete_comment(self):
        """Test user try to delete comment"""
        response = self.client.delete(
            reverse('api:comments-detail', kwargs={'pk': self.comment1.id}))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertTrue(Comment.objects.all().exists())

    def test_successful_comment_deletion(self):
        """Tests that moderators and superusers can delete comments"""

        self.user.is_moderator = True
        self.user.save()
        response = self.client.delete(
            reverse('api:comments-detail', kwargs={'pk': self.comment1.id}))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(Comment.objects.all().exists())

        self.comment1 = CommentFactory(author=self.user, post=self.post)
        self.user.is_moderator = False
        self.user.is_superuser = True
        self.user.save()

        response = self.client.delete(
            reverse('api:comments-detail', kwargs={'pk': self.comment1.id}))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(Comment.objects.all().exists())
Ejemplo n.º 22
0
    def test_all_games_from_same_group(self, mock_has_perm):
        mock_has_perm.return_value = True

        event = EventFactory()
        user = UserFactory()
        other_group = GroupFactory()
        games_user_group = GameFactory.create_batch(
            3, group=user.group, creator=user, event=event
        )
        games_other_group = GameFactory.create_batch(
            3, group=other_group, creator=user, event=event
        )
        self.client.force_login(user)
        response = self.client.get(
            reverse(
                "booking:event_games_group",
                kwargs={
                    "event_slug": event.slug,
                    "group_slug": user.group.slug,
                },
            ),
        )
        self.assertEqual(response.context["current_group"], user.group)
        for game in games_other_group:
            self.assertNotIn(
                game,
                response.context["games"][game.day][game.part_of_day],
                "game from other group is part of context",
            )
        for game in games_user_group:
            self.assertIn(
                game,
                response.context["games"][game.day][game.part_of_day],
                "game from own group is not part of context",
            )
        # Now check with reversed groups
        response = self.client.get(
            reverse(
                "booking:event_games_group",
                kwargs={
                    "event_slug": event.slug,
                    "group_slug": other_group.slug,
                },
            ),
        )
        self.assertEqual(response.context["current_group"], other_group)
        for game in games_other_group:
            self.assertIn(
                game,
                response.context["games"][game.day][game.part_of_day],
                "game from other group is not part of context",
            )
        for game in games_user_group:
            self.assertNotIn(
                game,
                response.context["games"][game.day][game.part_of_day],
                "game from own group is part of context",
            )
        mock_has_perm.assert_any_call(user, "booking.view_others_groups_bookings", None)
Ejemplo n.º 23
0
 def setUp(self):
     self.user = UserFactory()
     self.school = SchoolFactory()
     self.student = StudentFactory(
         user=self.user,
         school=self.school,
         date_of_birth=timezone.datetime(1994, 2, 5),
     )
Ejemplo n.º 24
0
 def test_it_works(self, graphql_client, fake_soap_call,
                   django_file_storage):
     user = UserFactory.create()
     graphql_client.request.user = user
     fake_soap_call.simulate_success(user)
     result = execute_genpdf_mutation(graphql_client)
     assert result['errors'] == []
     assert get_upload_status_for_user(user) == HPUploadStatus.SUCCEEDED
Ejemplo n.º 25
0
 def test_it_does_not_complain_when_existing_user_submits_their_own_email(
         self, db, rf):
     user = UserFactory(email="*****@*****.**")
     form = OptionalUniqueEmailForm(data={"email": "*****@*****.**"})
     req = rf.post("/")
     req.user = user
     form.set_request(req)
     assert form.errors == {}
Ejemplo n.º 26
0
 def setUp(self):
     self.user = UserFactory.build()
     self.user.save()
     self.ledger = LedgerFactory.build()
     self.ledger.user = self.user
     self.ledger.save()
     self.url = reverse('api:ledger-detail', kwargs={'pk': self.ledger.pk})
     self.client.credentials(HTTP_AUTHORIZATION='Token {}'.format(self.user.auth_token))
Ejemplo n.º 27
0
 def test_cannot_view_hidden_event(self):
     event = EventFactory(visible=False)
     self.client.force_login(UserFactory())
     response = self.client.get(event.get_absolute_url())
     self.assertTemplateUsed(response, "jeugdraad/alert.html")
     self.assertEqual(
         response.context["message"], "You are not allowed to view this event"
     )
Ejemplo n.º 28
0
 def setUp(self):
     self.user = UserFactory()
     self.order_1 = OrderFactory()
     self.order_2 = OrderFactory()
     self.order_3 = OrderFactory()
     self.order_4 = OrderFactory()
     self.asset = AssetFactory(symbol="TEST")
     self.strategy = StrategyFactory(asset=self.asset)
Ejemplo n.º 29
0
    def test_author_detail_returns_200_given_valid_input(self):
        user = UserFactory(is_staff=True)
        token = TokenFactory(user=user)
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

        response = self.client.get(self.url)

        self.assertEqual(200, response.status_code)
Ejemplo n.º 30
0
def test_admin_envelopes_pdf_is_inaccessible_to_non_staff_users(client):
    user = UserFactory()
    client.force_login(user)

    res = client.get(reverse('loc_envelopes'))

    assert res.status_code == 302
    assert res.url == f"/login?next={reverse('loc_envelopes')}"
Ejemplo n.º 31
0
 def test_they_return_none_when_user_has_no_recommendation(
         self, db, graphql_client):
     graphql_client.request.user = UserFactory()
     res = graphql_client.execute(self.QUERY)
     assert res["data"] == {
         "recommendedHpLandlord": None,
         "recommendedHpManagementCompany": None,
     }
Ejemplo n.º 32
0
    def setUp(self):
        self.user = UserFactory()

        self.request = RequestFactory().get("./fake_path")
        self.request.session = self.client.session
        self.request.user = self.user

        self.school = SchoolFactory(user=self.user)
Ejemplo n.º 33
0
 def test_requests(self):
     user = UserFactory.create()
     book = BookFactory.create()
     request = BookRequest(book=book, requester=user)
     request.save()
     self.assertEqual(list(book.requests()), [request])
Ejemplo n.º 34
0
 def setUp(self):
     self.client = APIClient(enforce_csrf_checks=True)
     self.user = UserFactory.create()  # suppress @UndefinedVariable
     self.auth = 'JWT {}'.format(self.create_token(self.user))
Ejemplo n.º 35
0
 def setUp(self):
     self.client = Client()
     self.book = BookFactory.create()
     self.user = UserFactory.create()