예제 #1
0
 def setUp(self):
     self.fake = Faker()
     self.view = views.update_profile()
     self.user = UserFactory()
     self.data = {
         'username':
         self.fake.user_name(),
         'firstname':
         self.fake.first_name(),
         'lastname':
         self.fake.last_name(),
         'date_of_birth':
         self.fake.date_of_birth(),
         'image':
         factory.django.ImageField(
             from_path=
             r"C:\Users\Elisha\Pictures\Screenshots\Screenshot (16).png",
             filename=r"\profile_pics\newimage",
             format="png")
     }
     self.request = RequestFactory().post(reverse('profile_update'),
                                          self.data)
     self.request.user = self.user
     self.response = views.update_profile.as_view()(self.request)
     self.user.refresh_from_db()
예제 #2
0
    def test_superuer_can_view_instance(self):
        user = UserFactory(is_superuser=True)

        secret = SecretFactory()

        assert user.has_perm("secret.view_secret", secret)

        assert user.has_perm("secret.change_secret", secret)
예제 #3
0
 def setUp(self):
     self.fake = Faker()
     self.view = views.update_profile()
     self.user = UserFactory()
     self.request = RequestFactory().get(reverse('profile_update'))
     self.request.user = self.user
     self.response = views.update_profile.as_view()(self.request)
     self.user.refresh_from_db()
예제 #4
0
 def setUp(self):
     self.view = views.UserPostListView
     self.user1 = UserFactory()
     self.user2 = UserFactory()
     self.url = reverse('blog:user-posts',
                        kwargs={'username': self.user1.username})
     self.posts_user1 = PostFactory.create_batch(2, author=self.user1)
     self.request = RequestFactory().get(self.url)
     self.response = self.view.as_view()(self.request,
                                         username=self.user1.username)
예제 #5
0
 def setUp(self):
     self.fake = Faker()
     self.view = views.update_profile()
     self.user = UserFactory()
     self.invalid_data = {
         'email': 'invalid_email',
         'date_of_birth': 'invalid_date'
     }
     self.request = RequestFactory().post(reverse('profile_update'),
                                          self.invalid_data)
     self.request.user = self.user
     self.response = views.update_profile.as_view()(self.request)
     self.user.refresh_from_db()
예제 #6
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,
            "password2": proto_user._password,
        })

        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
예제 #7
0
    def test_verify_audit_events_are_created(self, client):
        secret = SecretFactory()

        permission_url = reverse("secret:permissions",
                                 kwargs={"pk": secret.pk})
        user = login_and_verify_user(client)

        assign_perm("change_secret", user, secret)

        target_user = UserFactory()

        assert Audit.objects.count() == 0
        response = client.post(
            permission_url,
            {
                "user": target_user.id,
                "permission": "change_secret"
            },
        )

        assert response.status_code == 302
        assert response.url == permission_url

        assert Audit.objects.count() == 1
        audit = Audit.objects.first()

        assert audit.user == user
        assert audit.timestamp == timezone.now()
        assert audit.secret == secret
        assert audit.action == Actions.add_permission.name
        assert audit.description == f"Permission level to set change_secret for {target_user}"
예제 #8
0
 def test_account_page(self):
     user = UserFactory()
     self.client.force_login(user)
     response = self.client.get(reverse('user:account'))
     self.assertEqual(response.status_code, 200)
     self.assertEqual(user, response.context['user'])
     self.assertEqual(user.addresses.first(), response.context['address'])
예제 #9
0
def test_create_audit_event_separate_secrets():

    secret = SecretFactory()
    secret2 = SecretFactory()

    user = UserFactory()
    create_audit_event(
        user,
        Actions.view_secret,
        description="I viewed a secret",
        secret=secret,
        report_once=True,
    )

    create_audit_event(
        user,
        Actions.view_secret,
        description="I viewed another secret",
        secret=secret2,
        report_once=True,
    )

    assert Audit.objects.count() == 2

    audit = Audit.objects.last()

    assert audit.timestamp == timezone.now()
    assert audit.description == "I viewed another secret"
예제 #10
0
def test_unverified_user_on_login_is_redirected_to_otp_verify(client):
    user = UserFactory(is_active=True, is_staff=True, two_factor_enabled=True)
    client.force_login(user)

    response = client.get(reverse("admin:login"))

    assert response.status_code == 302
    assert response.url == reverse("twofactor:verify")
예제 #11
0
def test_authenticated_but_unverified_user_is_redirected_to_login(client):
    user = UserFactory(is_active=True, is_staff=True, two_factor_enabled=True)
    client.force_login(user)

    response = client.get(reverse("admin:index"))

    assert response.status_code == 302
    assert response.url.startswith(reverse("admin:login"))
예제 #12
0
 def setUpTestData(cls):
     cls.user = UserFactory.create()
     cls.test_campaigns = PollCampaignFactory.create_batch(size=2)
     cls.options = PollOptionFactory.create_batch(
         size=3,
         campaign=cls.test_campaigns[0],
     )
     PollFactory.create(option=cls.options[0], user=cls.user)
예제 #13
0
def test_user_disabled(client):
    user = UserFactory(is_active=False, two_factor_enabled=True)

    client.force_login(user, backend="core.backends.CustomAuthbrokerBackend")

    response = client.get(reverse("secret:list"))

    assert response.status_code == 302
    assert response.url == reverse("user:disabled")
예제 #14
0
def test_authenticated_and_verified_user_can_access_admin(client):
    user = UserFactory(is_active=True, is_staff=True, two_factor_enabled=True)
    otp_verify_user(user, client)
    client.force_login(user)

    response = client.get(reverse("admin:login"))

    assert response.status_code == 302
    assert response.url == reverse("admin:index")
예제 #15
0
class TestGet(TestCase):
    def setUp(self):
        self.fake = Faker()
        self.view = views.update_profile()
        self.user = UserFactory()
        self.request = RequestFactory().get(reverse('profile_update'))
        self.request.user = self.user
        self.response = views.update_profile.as_view()(self.request)
        self.user.refresh_from_db()

    def test_status_code(self):
        self.assertEqual(self.response.status_code, 200)

    def test_uForm_is_in_context(self):
        self.assertIn('uForm', self.response.context_data)

    def test_pForm_is_in_context(self):
        self.assertIn('pForm', self.response.context_data)
예제 #16
0
def test_user_without_2fa_is_redirected_to_enrollment_page(client):
    user = UserFactory(is_active=True, two_factor_enabled=False)

    client.force_login(user)

    response = client.get(reverse("secret:list"))

    assert response.status_code == 302
    assert response.url == reverse("twofactor:enroll")
예제 #17
0
    def test_requires_confirmed_device(self, client):
        user = UserFactory(is_active=True)

        client.force_login(user)

        response = client.get(reverse("twofactor:verify"))

        assert response.status_code == 302
        assert response.url == reverse("twofactor:enroll")
예제 #18
0
    def test_validate_one_poll_per_user(self):
        campaign = PollCampaignFactory.create()
        user = UserFactory.create()
        self.assertTrue(validate_one_poll_per_user(campaign, user))

        option = PollOptionFactory.create(campaign=campaign)
        PollFactory.create(option=option, user=user)
        with self.assertRaises(ValidationError):
            validate_one_poll_per_user(campaign, user)
예제 #19
0
def login_and_verify_user(client, verify=True, **extra_user_args):
    user = UserFactory(two_factor_enabled=True, **extra_user_args)

    client.force_login(user)

    if verify:
        otp_verify_user(user, client)

    return user
예제 #20
0
    def test_superuser_gets_all_data(self, rf):
        user = UserFactory(is_superuser=True)
        SecretFactory.create_batch(5)

        request = rf.get("/some/url")
        request.user = user

        filter = SecretFilter(request=request, queryset=Secret.objects.all())

        assert filter.qs.count() == 5
예제 #21
0
    def test_permission(self, start_permissions, input, expected):
        secret = SecretFactory()
        user = UserFactory()

        for perm in start_permissions:
            assign_perm(perm, user, secret)

        secret.set_permission(user, input)

        assert set(get_perms(user, secret)) == expected
예제 #22
0
    def test_remove_permissions(self, start_permissions):
        secret = SecretFactory()
        user = UserFactory()

        for perm in start_permissions:
            assign_perm(perm, user, secret)

        secret.remove_permissions(user)

        assert get_perms(user, secret) == []
예제 #23
0
class TestUpdateFormInvalid(TestCase):
    def setUp(self):
        self.fake = Faker()
        self.view = views.update_profile()
        self.user = UserFactory()
        self.invalid_data = {
            'email': 'invalid_email',
            'date_of_birth': 'invalid_date'
        }
        self.request = RequestFactory().post(reverse('profile_update'),
                                             self.invalid_data)
        self.request.user = self.user
        self.response = views.update_profile.as_view()(self.request)
        self.user.refresh_from_db()

    def test_uForm_invalid(self):
        self.assertFalse(self.response.context_data['pForm'].is_valid())

    def test_pForm_invalid(self):
        self.assertFalse(self.response.context_data['uForm'].is_valid())
예제 #24
0
    def test_device_already_confirmed(self, client):
        """Check that the verification form has been removed"""

        user = UserFactory(is_active=True, two_factor_enabled=True)

        user.totpdevice_set.all().update(confirmed=True)

        client.force_login(user)
        response = client.get(reverse("twofactor:enroll"))
        html_content = response.content.decode("utf-8")
        assert "You have already enabled 2-factor authentication." in html_content
예제 #25
0
    def test_submit_wrong_code_results_in_error(self, client):
        user = UserFactory(is_active=True)
        client.force_login(user)

        # create the device
        client.get(reverse("twofactor:enroll"))

        response = client.post(reverse("twofactor:enroll"), {"code": "123456"})
        html_content = response.content.decode("utf-8")

        assert "Invalid token" in html_content
예제 #26
0
    def test_next_url_on_get(self, client):
        """Verify that a ?next= querystring is rendered as a hidden form tag"""
        user = UserFactory(is_active=True, two_factor_enabled=True)

        client.force_login(user)

        response = client.post(
            reverse("twofactor:verify") + "?next=/hello-world/")
        body_html = response.content.decode("utf-8")

        assert '<input type="hidden" name="next" value="/hello-world/">' in body_html
예제 #27
0
    def test_no_perms_no_results(self, rf):
        """If you have no permission you should see no results"""
        user = UserFactory()
        SecretFactory(name="aws-1")

        request = rf.get("/some/url")
        request.user = user

        filter = SecretFilter(request=request, queryset=Secret.objects.all())

        assert filter.qs.count() == 0
예제 #28
0
    def test_invalid_code(self, client):
        user = UserFactory(is_active=True, two_factor_enabled=True)

        client.force_login(user)

        response = client.post(reverse("twofactor:verify"),
                               {"otp_token": "wrong-token"})

        assert response.status_code == 200
        html_content = response.content.decode("utf-8")

        assert "Invalid token. Please make sure you have entered it correctly." in html_content
예제 #29
0
    def test_user_gets_results_with_change_permission(self, rf):
        user = UserFactory()
        secret = SecretFactory(name="aws-1")

        assign_perm("change_secret", user, secret)

        request = rf.get("/some/url")
        request.user = user

        filter = SecretFilter(request=request, queryset=Secret.objects.all())

        assert filter.qs.count() == 1
예제 #30
0
class TestUpdateViewMixin(TestCase):
    def setUp(self):
        self.fake = Faker()
        self.view = views.update_profile()
        self.user = UserFactory()
        self.data = {
            'username':
            self.fake.user_name(),
            'firstname':
            self.fake.first_name(),
            'lastname':
            self.fake.last_name(),
            'date_of_birth':
            self.fake.date_of_birth(),
            'image':
            factory.django.ImageField(
                from_path=
                r"C:\Users\Elisha\Pictures\Screenshots\Screenshot (16).png",
                filename=r"\profile_pics\newimage",
                format="png")
        }
        self.request = RequestFactory().post(reverse('profile_update'),
                                             self.data)
        self.request.user = self.user
        self.response = views.update_profile.as_view()(self.request)
        self.user.refresh_from_db()

    def test_success_url_redirect(self):

        self.assertEqual(self.response.status_code, 302)
        self.assertRedirects(self.response,
                             reverse('user_profile_detail'),
                             fetch_redirect_response=False)

    def test_user_updated_if_valid(self):
        self.assertEqual(self.user.username, self.data.get('username'))
        self.assertEqual(self.user.firstname, self.data.get('firstname'))
        self.assertEqual(self.user.lastname, self.data.get('lastname'))
        self.assertEqual(self.user.profile.date_of_birth,
                         self.data.get('date_of_birth'))