コード例 #1
0
    def test_no_user_permissions_raises_error(self):
        guid = self.node._id
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.view.as_view()(request, guid=guid, user_id=self.user)
コード例 #2
0
 def _get_valid_shib_meta(self, location="/"):
     request_factory = RequestFactory()
     test_request = request_factory.get(location)
     test_request.META.update(**SAMPLE_HEADERS)
     shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(test_request)
     self.assertFalse(error, "Generating shibboleth attribute mapping contains errors")
     return shib_meta
コード例 #3
0
ファイル: test_middleware.py プロジェクト: mozilla/kuma
def test_set_remote_addr_from_forwarded_for(rf, forwarded_for, remote_addr):
    '''SetRemoteAddrFromForwardedFor parses the X-Forwarded-For Header.'''
    rf = RequestFactory()
    middleware = SetRemoteAddrFromForwardedFor(lambda req: None)
    request = rf.get('/', HTTP_X_FORWARDED_FOR=forwarded_for)
    middleware(request)
    assert request.META['REMOTE_ADDR'] == remote_addr
コード例 #4
0
class LoginViewTestCase(TestCase):
    def setUp(self):
        self.view = TokenLoginView()
        self.factory = RequestFactory()

    def test_get(self):
        response = self.view.get(self.factory.get('/api/sso/authenticate'))
        user = DummyUser()

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response['Location'], '/login-with/{}/{}'.format(user.pk, user.get_login_token())
        )

    def test_get_link(self):
        response = self.view.get(self.factory.get('/api/sso/authenticate'), link='/test')
        user = DummyUser()

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response['Location'],
            '/login-with/{}/{}?next=%2Ftest'.format(user.pk, user.get_login_token())
        )

    def test_get_authentication_failed(self):
        request = self.factory.get('/api/sso/authenticate')
        request.fails = True

        response = self.view.get(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response['Location'],
            "/token/error?message='test%20message'"
        )
コード例 #5
0
ファイル: tests.py プロジェクト: jespino/pycones-web
def subscribe(email):
    data = {
        'user_email': email
    }
    request = RequestFactory().post('/', data)
    request.user = AnonymousUser()
    return subscribe_newsletter(request)
コード例 #6
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_authentication_create_user_with_id_and_attributes(monkeypatch, django_user_model, settings):
    """
    CAS_CREATE_USER_WITH_ID is True and the attributes are not provided.

    Should raise ImproperlyConfigured exception
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', None, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    assert not django_user_model.objects.filter(
        username='******',
    ).exists()

    settings.CAS_CREATE_USER_WITH_ID = True
    backend = backends.CASBackend()
    with pytest.raises(ImproperlyConfigured) as excinfo:
        user = backend.authenticate(
            request, ticket='fake-ticket', service='fake-service',
        )

    assert "CAS_CREATE_USER_WITH_ID is True, but no attributes were provided" in str(excinfo)
コード例 #7
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_authentication_creating_a_user(monkeypatch, django_user_model):
    """
    Test the case where CAS authentication is creating a new user.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    assert not django_user_model.objects.filter(
        username='******',
    ).exists()

    backend = backends.CASBackend()
    user = backend.authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert user is not None
    assert user.username == '*****@*****.**'
    assert django_user_model.objects.filter(
        username='******',
    ).exists()
コード例 #8
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_authentication_creates_a_user_with_id_attribute(monkeypatch, django_user_model, settings):
    """
    If CAS_CREATE_USER_WITH_ID is True and 'id' is in the attributes, use this
    field to get_or_create a User.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', {'id': 999, 'is_staff': True, 'is_superuser': False}, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    assert not django_user_model.objects.filter(
        username='******',
    ).exists()

    settings.CAS_CREATE_USER_WITH_ID = True
    backend = backends.CASBackend()
    user = backend.authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert user is not None
    assert user.username == '*****@*****.**'
    assert django_user_model.objects.filter(id=999).exists()
コード例 #9
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_authentication_create_user_with_id_and_user_exists(monkeypatch, django_user_model, settings):
    """
    If CAS_CREATE_USER_WITH_ID is True and and the User already exists, don't create another user.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', {'id': 999, 'is_staff': True, 'is_superuser': False}, None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    existing_user = django_user_model.objects.create_user('*****@*****.**', '', id=999)

    settings.CAS_CREATE_USER_WITH_ID = True
    backend = backends.CASBackend()
    user = backend.authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert django_user_model.objects.all().count() == 1
    assert user is not None
    assert user.username == '*****@*****.**'
    assert user.id == 999
    assert user == existing_user
コード例 #10
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_user_can_authenticate(monkeypatch, django_user_model):
    """
    Test CAS authentication failure.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', {'ticket': ticket, 'service': service}, None

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    user = backends.CASBackend().authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert user is not None

    class AllowNoneBackend(backends.CASBackend):
        def user_can_authenticate(self, user):
            return False

    user = AllowNoneBackend().authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert user is None
コード例 #11
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_cas_attributes_renaming_working(monkeypatch, settings):
    """
    Test to make sure attributes are renamed according to the setting file
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return '*****@*****.**', \
            {'ln': 'MyLastName','fn':'MyFirstName','unkownAttr':'knownAttr'}, \
            None

    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    settings.CAS_RENAME_ATTRIBUTES = {'ln':'last_name'}
    settings.CAS_APPLY_ATTRIBUTES_TO_USER = True

    backend = backends.CASBackend()
    user = backend.authenticate(request, ticket='fake-ticket',
                                service='fake-service')

    # Checking user data
    assert user is not None
    assert user.last_name == 'MyLastName'
    assert user.first_name == ''

    # checking session data
    session_attr = request.session['attributes']
    assert session_attr['fn'] == 'MyFirstName'
    assert session_attr['last_name'] == 'MyLastName'
    with pytest.raises(KeyError):
        session_attr['ln']
コード例 #12
0
class TestIsFilterSelected(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.jinja_engine = engines['wagtail-env']

    def _render_template_with_request(self, request):
        s = '{{ is_filter_selected("foo", "bar") }}'
        template = self.jinja_engine.from_string(s)
        return template.render({'request': request})

    def test_query_parameter_undefined_not_selected(self):
        request = self.factory.get('/')
        self.assertEqual(self._render_template_with_request(request), 'False')

    def test_query_parameter_defined_with_expected_value(self):
        request = self.factory.get('/?foo=bar')
        self.assertEqual(self._render_template_with_request(request), 'True')

    def test_query_parameter_defined_with_unexpected_value(self):
        request = self.factory.get('/?foo=baz')
        self.assertEqual(self._render_template_with_request(request), 'False')

    def test_query_parameter_defined_multiple_times(self):
        request = self.factory.get('/?foo=bar&foo=baz')
        self.assertEqual(self._render_template_with_request(request), 'True')

    def test_query_parameter_also_works_with_filter_prefix(self):
        request = self.factory.get('/?filter_foo=bar')
        self.assertEqual(self._render_template_with_request(request), 'True')
コード例 #13
0
ファイル: test_backend.py プロジェクト: danizen/django-cas-ng
def test_backend_for_failed_auth(monkeypatch, django_user_model):
    """
    Test CAS authentication failure.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return None, {}, None

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    assert not django_user_model.objects.filter(
        username='******',
    ).exists()

    backend = backends.CASBackend()
    user = backend.authenticate(
        request, ticket='fake-ticket', service='fake-service',
    )

    assert user is None
    assert not django_user_model.objects.filter(
        username='******',
    ).exists()
コード例 #14
0
ファイル: test_debug.py プロジェクト: ArcTanSusan/django
 def test_request_with_items_key(self):
     """
     An exception report can be generated for requests with 'items' in
     request GET, POST, FILES, or COOKIES QueryDicts.
     """
     # GET
     request = self.rf.get('/test_view/?items=Oops')
     reporter = ExceptionReporter(request, None, None, None)
     text = reporter.get_traceback_text()
     self.assertIn("items = 'Oops'", text)
     # POST
     request = self.rf.post('/test_view/', data={'items': 'Oops'})
     reporter = ExceptionReporter(request, None, None, None)
     text = reporter.get_traceback_text()
     self.assertIn("items = 'Oops'", text)
     # FILES
     fp = StringIO('filecontent')
     request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp})
     reporter = ExceptionReporter(request, None, None, None)
     text = reporter.get_traceback_text()
     self.assertIn('items = <InMemoryUploadedFile:', text)
     # COOKES
     rf = RequestFactory()
     rf.cookies['items'] = 'Oops'
     request = rf.get('/test_view/')
     reporter = ExceptionReporter(request, None, None, None)
     text = reporter.get_traceback_text()
     self.assertIn("items = 'Oops'", text)
コード例 #15
0
ファイル: tests.py プロジェクト: Alberick0/part3_realpython
    def test_registering_user_twice_cause_error_msg(self, save_mock):
        # request used to test the view
        my_request = RequestFactory()
        my_request.method = 'POST'
        my_request.POST = {}
        my_request.session = {}

        html = render_to_response(
            'register.html',
            {
                'form': self.get_MockUserForm(),
                'months': list(range(1, 12)),
                'publishable': settings.STRIPE_PUBLISHABLE,
                'soon': soon(),
                'user': None,
                'years': list(range(2011, 2036)),
            }
        )

        # mock out stripe to avoid their server
        with mock.patch('stripe.Customer') as stripe_mock:
            config = {'create.return_value': mock.Mock()}
            stripe_mock.configure_mock(**config)

            # run the test
            resp = register(my_request)

            # verify things are okay
            # self.assertEquals(resp.content, html.content)
            # self.assertEqual(resp.status_code, 200)
            # self.assertEqual(my_request.session, {})

            # assert there is no records in the DB
            users = User.objects.filter(email='*****@*****.**')
            self.assertEqual(len(users), 0)
コード例 #16
0
ファイル: tests.py プロジェクト: njuice/FortyTwoTestTask
class LandingViewTests(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='******', email='*****@*****.**',
            password='******')

    def test_index_view(self):
        """
            Response status must be 200.
            Page must contain dummy call-to-action button
            Show page only for non-authorized users
        """

        # Show page only for non-authorized users
        request = self.factory.get(reverse('landing:index'))
        request.user = AnonymousUser()
        response = index(request)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Sign in with Facebook')

        # Redirect for authorized user
        request = self.factory.get(reverse('landing:index'))
        request.user = self.user
        response = index(request)
        self.assertEqual(response.status_code, 302)
コード例 #17
0
ファイル: test_debug.py プロジェクト: ArcTanSusan/django
 def test_request_with_items_key(self):
     """
     An exception report can be generated for requests with 'items' in
     request GET, POST, FILES, or COOKIES QueryDicts.
     """
     value = '<td>items</td><td class="code"><pre>&#39;Oops&#39;</pre></td>'
     # GET
     request = self.rf.get('/test_view/?items=Oops')
     reporter = ExceptionReporter(request, None, None, None)
     html = reporter.get_traceback_html()
     self.assertInHTML(value, html)
     # POST
     request = self.rf.post('/test_view/', data={'items': 'Oops'})
     reporter = ExceptionReporter(request, None, None, None)
     html = reporter.get_traceback_html()
     self.assertInHTML(value, html)
     # FILES
     fp = StringIO('filecontent')
     request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp})
     reporter = ExceptionReporter(request, None, None, None)
     html = reporter.get_traceback_html()
     self.assertInHTML(
         '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: '
         'items (application/octet-stream)&gt;</pre></td>',
         html
     )
     # COOKES
     rf = RequestFactory()
     rf.cookies['items'] = 'Oops'
     request = rf.get('/test_view/')
     reporter = ExceptionReporter(request, None, None, None)
     html = reporter.get_traceback_html()
     self.assertInHTML('<td>items</td><td class="code"><pre>&#39;Oops&#39;</pre></td>', html)
コード例 #18
0
ファイル: tests.py プロジェクト: Stunning/django
    def test_accepts_args_and_request(self):
        """
        Ensure that the subject is also handled if being
        passed a request object.
        """
        message = "Custom message that says '%s' and '%s'"
        token1 = 'ping'
        token2 = 'pong'

        admin_email_handler = self.get_admin_email_handler(self.logger)
        # Backup then override original filters
        orig_filters = admin_email_handler.filters
        try:
            admin_email_handler.filters = []
            rf = RequestFactory()
            request = rf.get('/')
            self.logger.error(message, token1, token2,
                extra={
                    'status_code': 403,
                    'request': request,
                }
            )
            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
            self.assertEqual(mail.outbox[0].subject,
                             "-SuperAwesomeSubject-ERROR (internal IP): Custom message that says 'ping' and 'pong'")
        finally:
            # Restore original filters
            admin_email_handler.filters = orig_filters
コード例 #19
0
ファイル: models.py プロジェクト: ssaltzman/POET
    def test_request_factory(self):
        factory = RequestFactory()
        request = factory.get('/somewhere/')
        response = get_view(request)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'This is a test')
コード例 #20
0
class HitCountTestBase(TestCase):

    def setUp(self):
        self.post = Post.objects.create(title='my title', content='my text')
        self.hit_count = HitCount.objects.create(content_object=self.post)
        self.factory = RequestFactory()
        self.request_post = self.factory.post(
            '/',
            {'hitcountPK': self.hit_count.pk},
            REMOTE_ADDR="127.0.0.1",
            HTTP_USER_AGENT='my_clever_agent',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.request_get = self.factory.get(
            '/',
            REMOTE_ADDR="127.0.0.1",
            HTTP_USER_AGENT='my_clever_agent',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.engine = import_module(settings.SESSION_ENGINE)
        self.store = self.engine.SessionStore()
        self.store.save()
        self.request_post.session = self.store
        self.request_post.user = AnonymousUser()
        self.request_get.session = self.store
        self.request_get.user = AnonymousUser()
コード例 #21
0
class SimpleTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')

    def test_details(self):
        # Create an instance of a GET request.
        request = self.factory.get('/templates/contact')

        # Create an instance of a POST request.
        request = self.factory.post('/template/thanks', data={'username': '******', 'email': '*****@*****.**', 'password': '******'})

        # Recall that middleware are not supported. You can simulate a
        # logged-in user by setting request.user manually.
        request.user = self.user

        # Or you can simulate an anonymous user by setting request.user to
        # an AnonymousUser instance.
        request.user = AnonymousUser()

        # Test my_view() as if it were deployed at /customer/details
        # Use this syntax for class-based views.
        response = views.user(request)
        self.assertEqual(response.status_code, 200)
コード例 #22
0
    def get_site(self):
        """
        Return a Site or RequestSite instance for use in registration.

        """
        factory = RequestFactory()
        return get_current_site(factory.get('/'))
コード例 #23
0
ファイル: test_views.py プロジェクト: deone/vendor
    def test_index_post(self):
        self.c.post(reverse('login'), {'username': '******', 'password': '******'})

        factory = RequestFactory()
        session = SessionMiddleware()

        data_one = {'pin': '12345678901234', 'voucher_type': 'STD'}
        data_two = {'pin': '12345678901233', 'voucher_type': 'STD'}

        voucher_one = send_api_request(settings.VOUCHER_STUB_INSERT_URL, data_one)
        voucher_two = send_api_request(settings.VOUCHER_STUB_INSERT_URL, data_two)

        prices = get_price_choices('STD')

        vendor = Vendor.objects.create(user=self.user, company_name="Vender Inc.")
        request = factory.post(reverse('vend_standard'), data={'value': 5, 'quantity': 2})
        request.user = self.user

        response = index(request, template='vend/vend_standard.html', vend_form=VendStandardVoucherForm, prices=prices)

        data_one.update({'voucher_id': voucher_one['id']})
        data_two.update({'voucher_id': voucher_two['id']})
        send_api_request(settings.VOUCHER_STUB_DELETE_URL, data_one)
        send_api_request(settings.VOUCHER_STUB_DELETE_URL, data_two)

        self.assertEqual(response['Content-Type'], 'text/plain')
        self.assertNotEqual(response.content, '')
コード例 #24
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
        def test_method(self):
            rf = RequestFactory()
            post = rf.post('/')
            get = rf.get('/')

            class LimitPostView(RateLimitMixin, View):
                ratelimit_ip = True
                ratelimit_method = ['POST']
                ratelimit_rate = '1/m'

                def post(self, request, *args, **kwargs):
                    return request.limited
                get = post

            class LimitGetView(RateLimitMixin, View):
                ratelimit_ip = True
                ratelimit_method = ['POST', 'GET']
                ratelimit_rate = '1/m'

                def post(self, request, *args, **kwargs):
                    return request.limited
                get = post

            limit_post = LimitPostView.as_view()
            limit_get = LimitGetView.as_view()

            assert not limit_post(post), 'Do not limit first POST.'
            assert limit_post(post), 'Limit second POST.'
            assert not limit_post(get), 'Do not limit GET.'

            assert limit_get(post), 'Limit first POST.'
            assert limit_get(get), 'Limit first GET.'
コード例 #25
0
ファイル: test_utils.py プロジェクト: ashwin31/django-machina
class TestIpAddressExtractor(object):
    @pytest.fixture(autouse=True)
    def setup(self):
        self.factory = RequestFactory()

    def test_can_determine_the_ip_address_with_the_http_x_forwarded_for_header(self):
        # Setup
        request = self.factory.get('/')
        parameters = request.META.copy()
        parameters['HTTP_X_FORWARDED_FOR'] = faker.ipv4()
        request.META = parameters
        # Run
        ip_address = get_client_ip(request)
        # Check
        assert ip_address == parameters['HTTP_X_FORWARDED_FOR']

    def test_can_determine_the_ip_address_with_the_remote_addr_header(self):
        # Setup
        request = self.factory.get('/')
        parameters = request.META.copy()
        parameters['HTTP_X_FORWARDED_FOR'] = None
        parameters['REMOTE_ADDR'] = faker.ipv4()
        request.META = parameters
        # Run
        ip_address = get_client_ip(request)
        # Check
        assert ip_address == parameters['REMOTE_ADDR']
コード例 #26
0
class TestShowUnTakenPollMessage(TestCase):
    def setUp(self):
        self.latest_poll_singleton = LatestPoll.get_solo()
        self.latest_poll_singleton.poll_id = 1
        self.latest_poll_singleton.flow_uuid = "flow uuid"
        self.latest_poll_singleton.save()
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**')
        self.reporter = Ureporter.objects \
            .create(last_poll_taken=1, subscribed=True,
                    user=self.user)

    @patch('webparticipation.apps.latest_poll.decorators.complete_run_already_exists')
    def test_should_show_message_if_user_has_no_completed_latest_poll(self, mock_complete_run):
        mock_complete_run.return_value = False
        request = self.factory.get('/?lp=true')
        request.session = MagicMock()
        request.user = self.user
        response = test_view(request)
        self.assertEqual(True, response.session.lp)

    @patch('webparticipation.apps.latest_poll.decorators.complete_run_already_exists')
    def test_should_not_show_message_if_user_has_completed_latest_poll(self, mock_complete_run):
        mock_complete_run.return_value = True
        request = self.factory.get('/?lp=true')
        request.session = MagicMock()
        request.user = self.user
        response = test_view(request)
        self.assertEqual(False, response.session.lp)
コード例 #27
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
    def test_keys(self):
        """Allow custom functions to set cache keys."""
        class User(object):
            def __init__(self, authenticated=False):
                self.pk = 1
                self.authenticated = authenticated

            def is_authenticated(self):
                return self.authenticated

        def user_or_ip(req):
            if req.user.is_authenticated():
                return 'uip:%d' % req.user.pk
            return 'uip:%s' % req.META['REMOTE_ADDR']

        @ratelimit(ip=False, rate='1/m', block=False, keys=user_or_ip)
        def view(request):
            return request.limited

        req = RequestFactory().post('/')
        req.user = User(authenticated=False)

        assert not view(req), 'First unauthenticated request is allowed.'
        assert view(req), 'Second unauthenticated request is limited.'

        del req.limited
        req.user = User(authenticated=True)

        assert not view(req), 'First authenticated request is allowed.'
        assert view(req), 'Second authenticated is limited.'
コード例 #28
0
class CommonUtilsTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_contact_form_response_status(self):
        request = self.factory.get('/common/contactForm')
        get_response = contact_form(request)
        assert get_response.status_code == 200, 'invalid response from GET request in common form: status %s' % get_response.status_code

        test_helper = CommonUtilsTestHelper()
        request.POST = test_helper.create_sample_post_dictionary(get_response)

        post_response = contact_form(request)
        assert post_response.status_code == 200, 'invalid response from POST response in common form: status %s' % post_response.status_code

    def test_contact_form_valid(self):
        request = self.factory.get('/common/contactForm')
        get_response = contact_form(request)
        test_helper = CommonUtilsTestHelper()
        request.POST = test_helper.create_sample_post_dictionary(get_response)
        assert get_response.status_code == 200, 'invalid response form GET request in common form: status %s' % get_response.status_code

        form = NewContactForm(request.POST)
        assert form.is_valid(), 'invalid contact form: %s' % form.is_valid()
コード例 #29
0
ファイル: templatetags.py プロジェクト: 1oscar/django-cms
    def test_cached_show_placeholder_sekizai(self):
        from django.core.cache import cache

        cache.clear()
        from cms.test_utils import project

        User = get_user_model()

        template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates',
                                    'show_placeholder')
        page = create_page('Test', 'col_two.html', 'en')
        placeholder = page.placeholders.all()[0]
        add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN')
        request = RequestFactory().get('/')
        request.user = User()
        request.current_page = page
        with SettingsOverride(TEMPLATE_DIRS=[template_dir]):
            template = Template(
                "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}")
            context = RequestContext(request, {'page': page, 'slot': placeholder.slot})
            output = template.render(context)
            self.assertIn('JAVASCRIPT', output)
            context = RequestContext(request, {'page': page, 'slot': placeholder.slot})
            output = template.render(context)
            self.assertIn('JAVASCRIPT', output)
コード例 #30
0
ファイル: tests.py プロジェクト: JiangJie/django
class ETagGZipMiddlewareTest(TestCase):
    """
    Tests if the ETag middleware behaves correctly with GZip middleware.
    """
    compressible_string = b'a' * 500

    def setUp(self):
        self.rf = RequestFactory()

    def test_compress_response(self):
        """
        Tests that ETag is changed after gzip compression is performed.
        """
        request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')
        response = GZipMiddleware().process_response(request,
            CommonMiddleware().process_response(request,
                HttpResponse(self.compressible_string)))
        gzip_etag = response.get('ETag')

        request = self.rf.get('/', HTTP_ACCEPT_ENCODING='')
        response = GZipMiddleware().process_response(request,
            CommonMiddleware().process_response(request,
                HttpResponse(self.compressible_string)))
        nogzip_etag = response.get('ETag')

        self.assertNotEqual(gzip_etag, nogzip_etag)
コード例 #31
0
ファイル: tests.py プロジェクト: Shibiraj/fb_page_manager
 def setUp(self):
     # Every test needs access to the request factory.
     self.factory = RequestFactory()
コード例 #32
0
class RegisteredUserTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    def test_user_show_page_content(self):
        with vcr.use_cassette('cassettes/logged_in_user_show'):
            user = User.objects.create_user('fake-user',
                                            '*****@*****.**',
                                            'johnpassword')
            user_homepage_request = self.factory.get('/acounts/profile/')
            user_homepage_request.user = user
            user_homepage_response = user_show(user_homepage_request)
            self.assertIn(b'Welcome fake-user!!!',
                          user_homepage_response.content)
            self.assertIn(b'Logout', user_homepage_response.content)
            self.assertNotIn(b'Login with Twitter',
                             user_homepage_response.content)

    def test_user_legislator_followed_relationship_displayed(self):
        with vcr.use_cassette('cassettes/user_followed_legislators'):
            legislator = Legislator.objects.create(
                first_name="Diana",
                last_name="DeGette",
                phone="12345",
                email="*****@*****.**",
                state_name="Colorado",
                pid="D000197",
                chamber="house",
                term_start="2017-01-03",
                term_end="2019-01-03",
                party="D",
                state="CO",
                cid="N00006134",
                twitter_id="RepDianaDeGette")
            user = User.objects.create_user('fake-user',
                                            '*****@*****.**',
                                            'johnpassword')
            legislator.users.add(user)

            user_homepage_request = self.factory.get('/acounts/profile/')
            user_homepage_request.user = user
            user_homepage_response = user_show(user_homepage_request)
            self.assertIn(b'Diana DeGette', user_homepage_response.content)
            self.assertIn(b'House', user_homepage_response.content)
            self.assertIn(b'CO-D', user_homepage_response.content)
            self.assertIn(b'Display Tweets from Diana',
                          user_homepage_response.content)
            self.assertIn(b'Unfollow Diana', user_homepage_response.content)

            legislator_show_request = self.factory.get(
                f'/legislators/{legislator.id}')
            legislator_show_request.user = user
            legislator_show_response = legislator_detail(
                legislator_show_request, legislator.id)
            self.assertIn(b'Unfollow', legislator_show_response.content)
            self.assertNotIn(b'Follow', legislator_show_response.content)

            user.legislator_set.remove(legislator)
            user_homepage_request = self.factory.get('/acounts/profile/')
            user_homepage_request.user = user
            user_homepage_response = user_show(user_homepage_request)
            self.assertNotIn(b'Diana DeGette', user_homepage_response.content)
            self.assertNotIn(b'House', user_homepage_response.content)
            self.assertNotIn(b'CO-D', user_homepage_response.content)
            self.assertNotIn(b'Display Tweets from Diana',
                             user_homepage_response.content)
            self.assertNotIn(b'Unfollow Diana', user_homepage_response.content)

            legislator_show_request = self.factory.get(
                f'/legislators/{legislator.id}')
            legislator_show_request.user = user
            legislator_show_response = legislator_detail(
                legislator_show_request, legislator.id)
            self.assertNotIn(b'Unfollow', legislator_show_response.content)
            self.assertIn(b'Follow', legislator_show_response.content)
コード例 #33
0
ファイル: conftest.py プロジェクト: weed0124/yondugram
def request_factory() -> RequestFactory:
    return RequestFactory()
コード例 #34
0
 def test_render_template(self, template):
     request = RequestFactory().get('/')
     context = Context({'request': request})
     Template('{%% load blog core bootstrap %%}%s' %
              template).render(context)
コード例 #35
0
 def setUpTestData(cls):
     super().setUpTestData()
     cls.request = RequestFactory()
     cls.context = RequestContext(cls.request)
コード例 #36
0
ファイル: tests.py プロジェクト: vbabiy/django-auditlog
 def setUp(self):
     self.middleware = AuditlogMiddleware()
     self.factory = RequestFactory()
     self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
コード例 #37
0
ファイル: tests.py プロジェクト: vbabiy/django-auditlog
class MiddlewareTest(TestCase):
    """
    Test the middleware responsible for connecting and disconnecting the signals used in automatic logging.
    """
    def setUp(self):
        self.middleware = AuditlogMiddleware()
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')

    def test_request_anonymous(self):
        """No actor will be logged when a user is not logged in."""
        # Create a request
        request = self.factory.get('/')
        request.user = AnonymousUser()

        # Run middleware
        self.middleware.process_request(request)

        # Validate result
        self.assertFalse(pre_save.has_listeners(LogEntry))

        # Finalize transaction
        self.middleware.process_exception(request, None)

    def test_request(self):
        """The actor will be logged when a user is logged in."""
        # Create a request
        request = self.factory.get('/')
        request.user = self.user
        # Run middleware
        self.middleware.process_request(request)

        # Validate result
        self.assertTrue(pre_save.has_listeners(LogEntry))

        # Finalize transaction
        self.middleware.process_exception(request, None)

    def test_response(self):
        """The signal will be disconnected when the request is processed."""
        # Create a request
        request = self.factory.get('/')
        request.user = self.user

        # Run middleware
        self.middleware.process_request(request)
        self.assertTrue(pre_save.has_listeners(LogEntry))  # The signal should be present before trying to disconnect it.
        self.middleware.process_response(request, HttpResponse())

        # Validate result
        self.assertFalse(pre_save.has_listeners(LogEntry))

    def test_exception(self):
        """The signal will be disconnected when an exception is raised."""
        # Create a request
        request = self.factory.get('/')
        request.user = self.user

        # Run middleware
        self.middleware.process_request(request)
        self.assertTrue(pre_save.has_listeners(LogEntry))  # The signal should be present before trying to disconnect it.
        self.middleware.process_exception(request, ValidationError("Test"))

        # Validate result
        self.assertFalse(pre_save.has_listeners(LogEntry))
コード例 #38
0
 def generate_context(self, user=None, files=None):
     request = RequestFactory()
     context_value = request.get("/graphql/")
     context_value.user = user or AnonymousUser()
     self.__set_context_files(context_value, files)
     return context_value
コード例 #39
0
def _prepare_request(url, user):
    request_factory = RequestFactory()
    request = request_factory.get(url)
    request.user = user
    return request
コード例 #40
0
ファイル: tests.py プロジェクト: WPMedia/muckrock
 def setUp(self):
     self.factory = RequestFactory()
     self.view = NewsletterSignupView.as_view()
     self.url = reverse("newsletter")
コード例 #41
0
 def setUp(self):
     request_factory = RequestFactory()
     self.test_request = request_factory.get('/')
     self.test_request.META.update(**SAMPLE_HEADERS)
class ExportCSVTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******',
                                             first_name='Test',
                                             last_name='Admin')
        self.jp = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******',
                                           first_name='J',
                                           last_name='Admin')

        VolunteerRecord.objects.create(activity="Planting trees",
                                       hours=2,
                                       date='2020-02-27',
                                       supervisor="Test Supervisor",
                                       owner=self.user)
        VolunteerRecord.objects.create(activity="Coding",
                                       hours=4,
                                       date='2020-03-27',
                                       supervisor="Test Supervisor",
                                       owner=self.user)
        VolunteerRecord.objects.create(activity="Testing",
                                       hours=3,
                                       date='2020-02-28',
                                       supervisor="Test Supervisor",
                                       owner=self.user)
        VolunteerRecord.objects.create(activity="Testing",
                                       hours=3,
                                       date='2020-02-28',
                                       supervisor="Test Supervisor",
                                       owner=self.jp)

    def test_activity_form_valid(self):
        form = FilterForm(data={
            'start_date': '2020-02-27',
            'end_date': '2020-02-28'
        })
        self.assertEquals(form.is_valid(), True)

    def test_activity_form_invalid_format(self):
        form = FilterForm(data={
            'start_date': '02-27-2020',
            'end_date': '02-28-2020'
        })
        self.assertEquals(form.is_valid(), False)

    def test_activity_form_invalid_input(self):
        form = FilterForm(data={
            'start_date': 'January 18th, 2020',
            'end_date': 'February 12th, 2020'
        })
        self.assertEquals(form.is_valid(), False)

    def test_activity_form_reversed_dates(self):
        form = FilterForm(data={
            'start_date': '2020-02-27',
            'end_date': '2020-01-28'
        })
        self.assertEquals(form.is_valid(), False)

    def test_activity_form_reversed_years(self):
        form = FilterForm(data={
            'start_date': '2021-01-28',
            'end_date': '2020-01-28'
        })
        self.assertEquals(form.is_valid(), False)

    def test_activity_form_reversed_months(self):
        form = FilterForm(data={
            'start_date': '2020-04-28',
            'end_date': '2020-01-28'
        })
        self.assertEquals(form.is_valid(), False)

    def test_activity_form_reversed_days(self):
        form = FilterForm(data={
            'start_date': '2020-01-30',
            'end_date': '2020-01-28'
        })
        self.assertEquals(form.is_valid(), False)

    def test_export_csv_normal_input(self):
        request = self.factory.post('/export/')
        request.user = self.user
        response = export_csv(request, '2020-02-27', '2020-03-28')
        split_response = response.content.decode('utf-8').rstrip().split('\n')

        for i in range(0, len(split_response)):
            split_response[i] = split_response[i].split(',')

        self.assertEquals(len(split_response), 4)

        self.assertEquals(split_response[0][0], 'Volunteer')
        self.assertEquals(split_response[0][1], 'Date')
        self.assertEquals(split_response[0][2], 'Hours')
        self.assertEquals(split_response[0][3], 'Description')

    def test_export_csv_same_date(self):
        request = self.factory.post('/export/')
        request.user = self.user
        response = export_csv(request, '2020-02-27', '2020-02-27')
        split_response = response.content.decode('utf-8').rstrip().split('\n')

        for i in range(0, len(split_response)):
            split_response[i] = split_response[i].split(',')

        self.assertEquals(len(split_response), 2)

        self.assertEquals(split_response[0][0], 'Volunteer')
        self.assertEquals(split_response[0][1], 'Date')
        self.assertEquals(split_response[0][2], 'Hours')
        self.assertEquals(split_response[0][3], 'Description')

        self.assertEquals(split_response[1][1], '2020-02-27')

    def test_export_csv_same_date_jp(self):
        request = self.factory.post('/export/')
        request.user = self.jp
        response = export_csv(request, '2020-02-28', '2020-02-28')
        split_response = response.content.decode('utf-8').rstrip().split('\n')

        for i in range(0, len(split_response)):
            split_response[i] = split_response[i].split(',')

        self.assertEquals(len(split_response), 2)

        self.assertEquals(split_response[0][0], 'Volunteer')
        self.assertEquals(split_response[0][1], 'Date')
        self.assertEquals(split_response[0][2], 'Hours')
        self.assertEquals(split_response[0][3], 'Description')

        self.assertEquals(split_response[1][1], '2020-02-28')
コード例 #43
0
ファイル: tests.py プロジェクト: amirrpp/auth_helenrich
class AccountPageLoginTest(TestCase):
    fixtures = ['test.json']

    def setUp(self):
        self.email = '*****@*****.**'
        self.username = '******'
        self.password = '******'
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username=self.username,
                                             email=self.email,
                                             password=self.password)

    def test_login_url_without_auth_user(self):
        request = self.factory.get(settings.LOGIN_URL)
        request.user = AnonymousUser()
        response = AccountAuthView.as_view()(request)

        self.assertEqual(response.status_code, 200)

    def test_login_url_with_auth_user(self):
        request = self.factory.get(settings.LOGIN_URL)
        request.user = self.user
        response = AccountAuthView.as_view()(request)

        self.assertEqual(response.status_code, 302)

    def test_login_button_without_auth_user(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()
        response = index_page(request)

        self.assertContains(response, 'Логин/Регистрация')
        self.assertContains(response, 'href="{}"'.format(settings.LOGIN_URL))

    def test_login_button_with_auth_user(self):
        request = self.factory.get('/')
        request.user = self.user
        response = index_page(request)

        self.assertContains(response, 'Здравствуйте, test')
        self.assertContains(response,
                            'href="{}"'.format(settings.LOGIN_REDIRECT_URL))

    def test_login_user(self):
        c = Client()
        response = c.post(settings.LOGIN_URL,
                          data={
                              'login-username': self.email,
                              'login-password': self.password,
                              'login_submit': LOGIN_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.wsgi_request.user,
                         User.objects.get(username=self.username))

    def test_login_user_with_bad_password(self):
        c = Client()
        response = c.post(settings.LOGIN_URL,
                          data={
                              'login-username': self.email,
                              'login-password': '******'.format(self.password),
                              'login_submit': LOGIN_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.wsgi_request.user,
                            User.objects.get(username=self.username))
        self.assertContains(response, BAD_PASSWORD)

    def test_login_user_required_fields(self):
        c = Client()
        response = c.post(settings.LOGIN_URL,
                          data={
                              'login-username': '',
                              'login-password': self.password,
                              'login_submit': LOGIN_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, REQUIRED_FIELD)

        response = c.post(settings.LOGIN_URL,
                          data={
                              'login-username': self.email,
                              'login-password': '',
                              'login_submit': LOGIN_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, REQUIRED_FIELD)

    def test_registration_user(self):
        c = Client()

        username = '******'

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '*****@*****.**',
                              'registration-username': username,
                              'registration-password1': 'secret',
                              'registration-password2': 'secret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 302)
        self.assertTrue(User.objects.filter(username=username).exists())
        self.assertEqual(response.wsgi_request.user,
                         User.objects.get(username=username))

    def test_registration_exists_user(self):
        c = Client()

        username = '******'

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': self.email,
                              'registration-username': username,
                              'registration-password1': 'secret',
                              'registration-password2': 'secret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.wsgi_request.user, AnonymousUser())
        self.assertContains(response, USER_IS_EXiSTS)

    def test_registration_user_different_password(self):
        c = Client()

        username = '******'

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '*****@*****.**',
                              'registration-username': username,
                              'registration-password1': 'supersecret',
                              'registration-password2': 'extrasecret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertEqual(response.status_code, 200)
        self.assertFalse(User.objects.filter(username=username).exists())
        self.assertEqual(response.wsgi_request.user, AnonymousUser())
        self.assertContains(response,
                            _("The two password fields didn't match."))

    def test_registration_user_required_fields(self):
        c = Client()

        username = '******'

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '',
                              'registration-username': username,
                              'registration-password1': 'secret',
                              'registration-password2': 'secret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertContains(response, REQUIRED_FIELD)

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '*****@*****.**',
                              'registration-username': '',
                              'registration-password1': 'secret',
                              'registration-password2': 'secret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertContains(response, REQUIRED_FIELD)

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '*****@*****.**',
                              'registration-username': username,
                              'registration-password1': '',
                              'registration-password2': 'secret',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertContains(response, REQUIRED_FIELD)

        response = c.post(settings.LOGIN_URL,
                          data={
                              'registration-email': '*****@*****.**',
                              'registration-username': username,
                              'registration-password1': 'secret',
                              'registration-password2': '',
                              'registration_submit': REGISTRATION_BUTTON_LABEL,
                          })

        self.assertContains(response, REQUIRED_FIELD)
        self.assertEqual(response.status_code, 200)
        self.assertFalse(User.objects.filter(username=username).exists())
        self.assertEqual(response.wsgi_request.user, AnonymousUser())

    def test_logout(self):
        c = Client()
        c.login(username=self.email, password=self.password)

        response = c.get(settings.LOGOUT_URL)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.wsgi_request.user, AnonymousUser())
コード例 #44
0
 def setUp(self):
     self.rf = RequestFactory()
     self.url = reverse('kannel-backend', args=['kannel-backend'])
     self.conf = {}
     self.view = views.KannelBackendView.as_view(conf=self.conf)
コード例 #45
0
ファイル: tests.py プロジェクト: cluster311/ggg
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

        self.create_users_and_groups()
コード例 #46
0
 def setUp(self):
     self.request_factory = RequestFactory()
     self.smw = SessionMiddleware()
     self.amw = AuthenticationMiddleware()
     self.rmw = RemoteUserMiddleware()
     self.srmw = middleware.ShibbolethRemoteUserMiddleware()
コード例 #47
0
 def setUp(self):
     self.models = []
     self.factory = RequestFactory()
     self.models.append(TrialModel.objects.create(field1='first', field2=1))
     self.models.append(TrialModel.objects.create(field1='second',
                                                  field2=2))
コード例 #48
0
ファイル: tests.py プロジェクト: amirrpp/auth_helenrich
class AccountPageProfileTest(TestCase):
    fixtures = ['test.json']

    def setUp(self):
        self.email = '*****@*****.**'
        self.username = '******'
        self.password = '******'
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username=self.username,
                                             email=self.email,
                                             password=self.password)

    def test_profile_url_without_auth_user(self):
        request = self.factory.get(settings.LOGIN_REDIRECT_URL)
        request.user = AnonymousUser()
        response = AccountEditView.as_view()(request)

        self.assertEqual(response.status_code, 302)

    def test_profile_url_with_auth_user(self):
        request = self.factory.get(settings.LOGIN_REDIRECT_URL)
        request.user = self.user
        response = AccountEditView.as_view()(request)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'value="{}"'.format(self.username))
        self.assertContains(response, 'value="{}"'.format(self.email))

    def test_profile_change_email(self):
        c = Client()
        c.login(username=self.email, password=self.password)

        new_email = '*****@*****.**'

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': new_email,
                              'username': self.username,
                              'old_password': '',
                              'password1': '',
                              'password2': '',
                          })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            User.objects.get(username=self.username).email, new_email)

    def test_profile_change_email_to_exists(self):
        c = Client()

        new_email = '*****@*****.**'
        User.objects.create_user(username='******',
                                 email=new_email,
                                 password=self.password)

        c.login(username=self.email, password=self.password)

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': new_email,
                              'username': self.username,
                              'old_password': '',
                              'password1': '',
                              'password2': '',
                          })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.wsgi_request.user,
                         User.objects.get(username=self.username))
        self.assertEqual(
            User.objects.get(username=self.username).email, self.email)
        self.assertContains(response, USER_IS_EXiSTS)

    def test_profile_change_username(self):
        c = Client()
        c.login(username=self.email, password=self.password)

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': self.username + 'other',
                              'old_password': '',
                              'password1': '',
                              'password2': '',
                          })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            User.objects.get(email=self.email).username,
            self.username + 'other')

    def test_profile_change_password(self):
        c = Client()
        c.login(username=self.user.email, password=self.password)

        newpassword = '******'

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': self.username,
                              'old_password': self.password,
                              'password1': newpassword,
                              'password2': newpassword,
                          })

        user = authenticate(username=self.email, password=self.password)
        self.assertFalse(user)

        user = authenticate(username=self.email, password=newpassword)

        self.assertTrue(user)
        self.assertEqual(response.status_code, 302)

    def test_profile_change_password_with_bad_old_password(self):
        c = Client()
        c.login(username=self.user.email, password=self.password)

        newpassword = '******'

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': self.username,
                              'old_password': '******'.format(self.password),
                              'password1': newpassword,
                              'password2': newpassword,
                          })

        user = authenticate(username=self.email, password=newpassword)
        self.assertFalse(user)

        user = authenticate(username=self.email, password=self.password)
        self.assertTrue(user)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, BAD_PASSWORD)

    def test_profile_change_password_without_old_password(self):
        c = Client()
        c.login(username=self.user.email, password=self.password)

        newpassword = '******'

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': self.username,
                              'old_password': '',
                              'password1': newpassword,
                              'password2': newpassword,
                          })

        user = authenticate(username=self.email, password=newpassword)
        self.assertFalse(user)

        user = authenticate(username=self.email, password=self.password)
        self.assertTrue(user)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, BAD_PASSWORD)

    def test_profile_change_password_with_old_password_and_without_new_password(
            self):
        c = Client()
        c.login(username=self.user.email, password=self.password)

        newpassword = ''

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': self.username,
                              'old_password': self.password,
                              'password1': newpassword,
                              'password2': newpassword,
                          })

        user = authenticate(username=self.email, password=self.password)
        self.assertTrue(user)

        self.assertEqual(response.status_code, 302)

    def test_profile_set_email_to_empty(self):
        c = Client()
        c.login(username=self.email, password=self.password)

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': '',
                              'username': self.username,
                              'old_password': '',
                              'password1': '',
                              'password2': '',
                          })

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, REQUIRED_FIELD)

    def test_profile_set_username_to_empty(self):
        c = Client()
        c.login(username=self.email, password=self.password)

        response = c.post(settings.LOGIN_REDIRECT_URL,
                          data={
                              'email': self.email,
                              'username': '',
                              'old_password': '',
                              'password1': '',
                              'password2': '',
                          })

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, REQUIRED_FIELD)
コード例 #49
0
class IndexViewTest(TestCase):
    def test_index_shows_cirle_and_topics_names(self):
        client = get_logged_superuser_client()
        topic_name = "testTopic"
        circle_name = "testCircle"
        circle = CircleFactory.create(name=circle_name)
        topic = TopicFactory.create(name=topic_name, circle=circle)

        response = client.get("/")
        self.assertContains(response, circle_name)
        self.assertContains(response, topic_name)

    def test_index_with_no_circle_print_message(self):
        client = get_logged_superuser_client()

        response = client.get("/")
        self.assertContains(response, "No Circle available.")

    def test_index_with_no_topic_in_circle_print_message(self):
        client = get_logged_superuser_client()
        circle = CircleFactory.create()
        circle.save()

        response = client.get("/")
        self.assertContains(response, "No Topics available.")

    def test_index_shows_topics_numbers(self):
        client = get_logged_superuser_client()
        create_sample_with_score_values([1, 1, 0, 1])

        response = client.get("/")

        self.assertContains(
            response,
            'topic0 : <span class="badge dark-grey-bg text-white">1</span>')
        self.assertContains(
            response,
            'topic1 : <span class="badge dark-grey-bg text-white">1</span>')
        self.assertContains(
            response,
            'topic2 : <span class="badge dark-grey-bg text-white">0</span>')
        self.assertContains(
            response,
            'topic3 : <span class="badge dark-grey-bg text-white">1</span>')

    def test_filtered_view_shows_only_selected_range_of_values(self):
        client = get_logged_superuser_client()
        create_sample_with_score_values([1, 5, 4, 2])
        circle_id = Topic.objects.filter(name="topic0").first().circle.id

        response = client.get("/", {f"topic_value_gt_{circle_id}": 3})
        self.assertContains(
            response,
            'topic0 : <span class="badge dark-grey-bg text-white">0</span>')
        self.assertContains(
            response,
            'topic1 : <span class="badge dark-grey-bg text-white">1</span>')
        self.assertContains(
            response,
            'topic2 : <span class="badge dark-grey-bg text-white">1</span>')
        self.assertContains(
            response,
            'topic3 : <span class="badge dark-grey-bg text-white">0</span>')

    def test_filtered_view_shows_only_selected_dimensions_score(self):
        client = get_logged_superuser_client()
        circle = CircleFactory.create()
        topic = TopicFactory.create(name="topic", circle=circle)
        dimension_one = DimensionFactory.create(name="dimension_one",
                                                topic=topic)
        dimension_two = DimensionFactory.create(name="dimension_two",
                                                topic=topic)
        people = create_users(2)

        score_first = Score(person=people[0], dimension=dimension_one, value=5)
        score_first.save()
        score_second = Score(person=people[1],
                             dimension=dimension_two,
                             value=5)
        score_second.save()

        response = client.get(
            "/", {f"topic_dimension_eq_{circle.id}": dimension_one.id})
        self.assertContains(
            response,
            'topic : <span class="badge dark-grey-bg text-white">1</span>')

    def test_index_add_expected_context(self):
        create_sample_with_score_values([1, 1, 0, 1])
        topics_names = ["topic0", "topic1", "topic2", "topic3"]
        self.factory = RequestFactory()
        request = self.factory.get("/")
        index = IndexView()
        index.setup(request)

        context = index.add_circles_context({})
        self.assertNotEqual(context.get("circles"), None)
        circle = context["circles"]
        self.assertNotEqual(circle.get("circle"), None)

        topics_details = circle["circle"]["topics_details"]
        for topic_name in topics_names:
            self.assertNotEqual(topics_details.get(topic_name), None)

    def test_count_people_in_topic_return_expected_value(self):
        circle = CircleFactory.create()
        topic = TopicFactory(circle=circle)
        dimension = DimensionFactory(topic=topic)
        dimension.save()
        people = create_users(2)

        score_first = Score(person=people[0], dimension=dimension, value=0)
        score_first.save()
        score_second = Score(person=people[1], dimension=dimension, value=1)
        score_second.save()

        index = IndexView()
        value = index.count_people_in_topic(topic)

        self.assertEqual(value, 1)

    def test_index_view_shows_all_circle_names(self):
        client = get_logged_superuser_client()
        circles = [CircleFactory.create() for _ in range(4)]
        circles_names = [circle.name for circle in circles]

        response = client.get("/")

        for name in circles_names:
            self.assertContains(response, name)

    def test_index_view_shows_all_topics_of_different_circles(self):
        client = get_logged_superuser_client()
        first_circle = CircleFactory.create()
        second_circle = CircleFactory.create()
        first_circle_topics = [
            TopicFactory.create(circle=first_circle) for _ in range(3)
        ]
        second_circle_topics = [
            TopicFactory.create(circle=second_circle) for _ in range(3)
        ]

        response = client.get("/")

        topics_names = [topic.name for topic in first_circle_topics
                        ] + [topic.name for topic in second_circle_topics]
        for topic_name in topics_names:
            self.assertContains(response, topic_name)

    def test_alter_circle_value_filter_not_alter_others_circle_value_filter(
            self):
        client = get_logged_superuser_client()
        person = create_users(1)[0]
        first_circle = CircleFactory.create()
        second_circle = CircleFactory.create()
        first_circle_topic = TopicFactory.create(circle=first_circle)
        second_circle_topic = TopicFactory.create(circle=second_circle)
        first_circle_dimension = DimensionFactory.create(
            topic=first_circle_topic)
        second_circle_dimension = DimensionFactory.create(
            topic=second_circle_topic)
        first_circle_score = ScoreFactory.create(
            dimension=first_circle_dimension, value=3, person=person)
        second_circle_score = ScoreFactory.create(
            dimension=second_circle_dimension, value=3, person=person)

        response = client.get("/", {f"topic_value_gt_{first_circle.id}": 4})

        self.assertContains(
            response,
            f'{first_circle_topic.name} : <span class="badge dark-grey-bg text-white">0</span>',
        )
        self.assertContains(
            response,
            f'{second_circle_topic.name} : <span class="badge dark-grey-bg text-white">1</span>',
        )

    def test_alter_circle_dimension_filter_not_alter_others_circle_dimension_filter(
        self, ):
        client = get_logged_superuser_client()
        person = create_users(1)[0]
        first_circle = CircleFactory.create()
        second_circle = CircleFactory.create()
        first_circle_topic = TopicFactory.create(circle=first_circle)
        second_circle_topic = TopicFactory.create(circle=second_circle)
        first_circle_dimension_populated = DimensionFactory.create(
            name="dimension_1", topic=first_circle_topic)
        first_circle_dimension_empty = DimensionFactory.create(
            name="dimension_2", topic=first_circle_topic)
        second_circle_dimension = DimensionFactory.create(
            name="dimension_1", topic=second_circle_topic)
        first_circle_score = ScoreFactory.create(
            dimension=first_circle_dimension_populated, person=person)
        second_circle_score = ScoreFactory.create(
            dimension=second_circle_dimension, person=person)

        response = client.get(
            "/",
            {
                f"topic_dimension_eq_{first_circle.id}":
                f"{first_circle_dimension_empty.id}"
            },
        )

        self.assertContains(
            response,
            f'{first_circle_topic.name} : <span class="badge dark-grey-bg text-white">0</span>',
        )
        self.assertContains(
            response,
            f'{second_circle_topic.name} : <span class="badge dark-grey-bg text-white">1</span>',
        )

    def test_not_logged_person_accessing_index_will_be_redirect_to_login_page(
            self):
        client = Client()

        response = client.get("/", follow=True)

        self.assertContains(response, "Login")

    def test_normal_logged_user_can_access_index_view(self):
        user_username = "******"
        user_psw = "mypasspass"
        user = UserFactory.build(username=user_username, password=user_psw)
        user.save()
        client = Client()
        client.login(username=user_username, password=user_psw)

        response = client.get("/")

        self.assertContains(response, "No Circle available")
コード例 #50
0
ファイル: test_views.py プロジェクト: pedrogzvargas/tutorias
    def test_case_sensitivity(self, rf: RequestFactory):
        request = rf.get("/fake-url/")
        request.user = UserFactory(username="******")

        with pytest.raises(Http404):
            user_detail_view(request, username="******")
コード例 #51
0
 def setUp(self):
     self.request = RequestFactory().get('/')
     user = AnonymousUser()  # technically, Anonymous users cannot access the admin
     self.request.user = user
from django.template import engines, Template, Context
from django.test import RequestFactory

from csp.middleware import CSPMiddleware

JINJA_ENV = engines['jinja2']
mw = CSPMiddleware()
rf = RequestFactory()


class ScriptTestBase(object):
    def assert_template_eq(self, tpl1, tpl2):
        aaa = tpl1.replace('\n', '').replace('  ', '')
        bbb = tpl2.replace('\n', '').replace('  ', '')
        assert aaa == bbb

    def process_templates(self, tpl, expected):
        request = rf.get('/')
        mw.process_request(request)
        ctx = self.make_context(request)
        return (self.make_template(tpl).render(ctx).strip(),
                expected.format(request.csp_nonce))


class ScriptTagTestBase(ScriptTestBase):
    def make_context(self, request):
        return Context({'request': request})

    def make_template(self, tpl):
        return Template(tpl)
コード例 #53
0
ファイル: tests.py プロジェクト: tadeoos/django-smart-lists
class SmartListTestCase(TestCase):
    def setUp(self):
        self.sample = SampleModel.objects.create(
            title='I just love django-smart-lists!', category='blog_post')
        self.factory = RequestFactory()

    def test_columns(self):
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', 'category'))

        self.assertEqual(len(smart_list.columns), 2)

    def test_illegal_method_list_display(self):
        self.assertRaises(SmartListException,
                          SmartList,
                          SampleModel.objects.all(),
                          list_display=('delete', ))

        self.assertRaises(SmartListException,
                          SmartList,
                          SampleModel.objects.all(),
                          list_display=('_delete', ))

    def test_ordering_of_columns(self):
        smart_list = SmartList(
            SampleModel.objects.all(), **{
                'list_display': ('title', 'category', 'some_display_method',
                                 'friendly_category')
            })

        self.assertEqual(smart_list.columns[0].order_field, 'title')
        self.assertEqual(smart_list.columns[0].order.column_id, 1)
        self.assertEqual(smart_list.columns[1].order_field, 'category')
        self.assertEqual(smart_list.columns[1].order.column_id, 2)
        self.assertEqual(smart_list.columns[2].order_field, None)
        self.assertEqual(smart_list.columns[2].order, None)
        self.assertEqual(smart_list.columns[3].order_field, 'category')
        self.assertEqual(smart_list.columns[3].order.column_id, 4)

    def test_ordering_in_queryset(self):
        class SampleModelListView(SmartListMixin, ListView):
            model = SampleModel
            list_display = ('title', 'category')

        request = self.factory.get('/smart-lists/')
        view = SampleModelListView(request=request)
        self.assertEqual(view.get_ordering(), [])

        request = self.factory.get('/smart-lists/?o=1')
        view = SampleModelListView(request=request)
        self.assertEqual(view.get_ordering(), ['title'])

        request = self.factory.get('/smart-lists/?o=2.1')
        view = SampleModelListView(request=request)
        self.assertEqual(view.get_ordering(), ['category', 'title'])

        request = self.factory.get('/smart-lists/?o=-2.1')
        view = SampleModelListView(request=request)
        self.assertEqual(view.get_ordering(), ['-category', 'title'])

        request = self.factory.get('/smart-lists/?o=-wqdwd')
        view = SampleModelListView(request=request)
        self.assertRaises(SmartListException, view.get_ordering)

        request = self.factory.get('/smart-lists/?o=5')
        view = SampleModelListView(request=request)
        self.assertRaises(SmartListException, view.get_ordering)

    def test_smart_order(self):
        so = SmartOrder({'o': '1.2'}, 1, 'o')
        self.assertEqual(so.is_ordered(), True)
        self.assertEqual(so.is_reverse(), False)

        so = SmartOrder({'o': '-1.2'}, 1, 'o')
        self.assertEqual(so.is_ordered(), True)
        self.assertEqual(so.is_reverse(), True)

        so = SmartOrder({'o': '-1.2'}, 2, 'o')
        self.assertEqual(so.is_ordered(), True)
        self.assertEqual(so.is_reverse(), False)
        self.assertEqual(so.get_add_sort_by(), '?o=2.-1')

        so = SmartOrder({'o': '1'}, 1, 'o')
        self.assertEqual(so.is_ordered(), True)
        self.assertEqual(so.is_reverse(), False)
        self.assertEqual(so.get_add_sort_by(), '?o=-1')

    def test_get_verbose_column_title_with_fallback(self):
        smart_list = SmartList(SampleModel.objects.all(),
                               **{'list_display': ('category', )})
        self.assertEqual('Category', smart_list.columns[0].get_title())

    def test_get_column_from_method(self):
        smart_list = SmartList(SampleModel.objects.all(),
                               **{'list_display': ('some_display_method', )})
        self.assertEqual('Some Display Method',
                         smart_list.columns[0].get_title())
        self.assertEqual('I just love django-smart-lists! blog_post',
                         smart_list.items[0].fields()[0].get_value())

    def test_search(self):
        test = SampleModel.objects.create(title='test')
        foobar = SampleModel.objects.create(title='foobar')
        bar = SampleModel.objects.create(title='bar')

        class SampleModelListView(SmartListMixin, ListView):
            model = SampleModel
            list_display = ('title', 'category')
            search_fields = ('title', )

        request = self.factory.get('/smart-lists/?q=test')
        view = SampleModelListView(request=request)
        self.assertEqual(1, len(view.get_queryset()))
        self.assertEqual(test, view.get_queryset()[0])

        request = self.factory.get('/smart-lists/?q=bar')
        view = SampleModelListView(request=request)
        self.assertEqual(2, len(view.get_queryset()))
        self.assertEqual([foobar, bar], list(view.get_queryset()))

    def test_custom_filter_classes_parsing(self):
        class BlogOrNotFilter(SmartListFilter):
            parameter_name = 'blog'
            title = 'BlogOrNot'

            def lookups(self):
                return (('blog', 'Blog'), ('orNot', 'OR NOT!'))

            def queryset(self, queryset):
                if self.value() == 'blog':
                    return queryset.filter(category="blog_post")
                if self.value() == 'blog':
                    return queryset.exclude(category="blog_post")
                return queryset

        request = self.factory.get('/smart-lists/')
        smart_list = SmartList(
            SampleModel.objects.all(),
            list_display=('title', 'category'),
            list_filter=(BlogOrNotFilter(request), 'category'),
        )

        fltr = smart_list.filters[0]
        self.assertEqual(fltr.get_title(), 'BlogOrNot')

        values = fltr.get_values()
        self.assertEqual(values[0].get_title(), 'All')
        self.assertEqual(values[0].is_active(), True)
        self.assertEqual(values[1].get_title(), 'Blog')
        self.assertEqual(values[1].is_active(), False)
        self.assertEqual(values[2].get_title(), 'OR NOT!')
        self.assertEqual(values[2].is_active(), False)

        request = self.factory.get('/smart-lists/?blog=blog')
        smart_list = SmartList(
            SampleModel.objects.all(),
            list_display=('title', 'category'),
            list_filter=(BlogOrNotFilter(request), ),
            query_params=request.GET,
        )

        fltr = smart_list.filters[0]
        values = fltr.get_values()
        self.assertEqual(values[0].is_active(), False)
        self.assertEqual(values[1].is_active(), True)
        self.assertEqual(values[2].is_active(), False)

    def test_custom_filter_classes_query(self):
        test = SampleModel.objects.create(title='test', category="blog_post")
        foo = SampleModel.objects.create(title='foo', category="foo")
        bar = SampleModel.objects.create(title='bar', category="bar")

        class BlogOrNotFilter(SmartListFilter):
            parameter_name = 'blog'
            title = 'BlogOrNot'

            def lookups(self):
                return (('blog', 'Blog'), ('orNot', 'OR NOT!'))

            def queryset(self, queryset):
                if self.value() == 'blog':
                    return queryset.filter(category="blog_post")
                if self.value() == 'blog':
                    return queryset.exclude(category="blog_post")
                return queryset

        class FakeView(SmartListMixin):
            list_filter = (BlogOrNotFilter, 'category')

        view = FakeView()

        request = self.factory.get('/smart-lists/')
        view.request = request
        self.assertEqual(
            view.smart_filter_queryset(SampleModel.objects.all()).count(),
            4)  # init makes one as well

        request = self.factory.get('/smart-lists/?blog=blog')
        view.request = request
        self.assertEqual(
            view.smart_filter_queryset(SampleModel.objects.all()).count(),
            2)  # init makes one as well

    def test_labels_for_columns(self):
        """Test if labels works properly."""
        label = 'Custom column label'
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', ('category', label)))

        column_with_custom_label = smart_list.columns[-1]

        self.assertEqual(label, column_with_custom_label.label)
        self.assertEqual(label, column_with_custom_label.get_title())

    def test_custom_html_column(self):
        """Test custom html column works properly."""
        render_column_function = lambda obj: SafeText(
            '<b>Custom column redered</b>')
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', (render_column_function,
                                                       'Column label')))

        smart_list_item_field_with_custom_render = smart_list.items[-1].fields(
        )[-1].get_value()

        self.assertEqual(render_column_function(SampleModel.objects.last()),
                         smart_list_item_field_with_custom_render)

    def test_new_filter_clears_pagination(self):
        request = self.factory.get(
            '/smart-lists/?page=2&o=1&category=blog_post')
        smart_list = SmartList(
            SampleModel.objects.all(),
            list_display=('title', 'category'),
            list_filter=('title', 'category'),
            query_params=request.GET,
        )
        fltr = smart_list.filters[0]
        url = fltr.get_values()[0].get_url()
        self.assertEqual(set(url[1:].split('&')),
                         set(['o=1', 'category=blog_post']))
コード例 #54
0
class TestTpaPipeline(unittest.TestCase):
    """
    Test functions in the tpa_pipeline module.
    """

    def setUp(self):
        ecidp = EnterpriseCustomerIdentityProviderFactory(provider_id='provider_slug')
        self.customer = ecidp.enterprise_customer
        self.user = UserFactory(is_active=True)
        self.request_factory = RequestFactory()
        self.request = self.request_factory.get('/')
        self.request.session = cache.SessionStore()
        super(TestTpaPipeline, self).setUp()

    def get_mocked_sso_backend(self):
        """
        Get a mocked request backend with mocked strategy.
        """
        # Monkey-patch storage for messaging;   pylint: disable=protected-access
        self.request._messages = fallback.FallbackStorage(self.request)

        strategy_mock = mock.MagicMock(request=self.request)
        backend = mock.MagicMock(
            name=None,
            strategy=strategy_mock,
        )
        return backend

    @ddt.data(False, True)
    def test_handle_enterprise_logistration_user_linking(
            self,
            user_is_active,
    ):
        """
        Test that we create an EnterpriseCustomerUser, then return.
        """
        backend = self.get_mocked_sso_backend()
        self.user = UserFactory(is_active=user_is_active)
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            enterprise_customer = EnterpriseCustomerFactory(
                enable_data_sharing_consent=False
            )
            fake_get_ec.return_value = enterprise_customer
            assert handle_enterprise_logistration(backend, self.user) is None
            assert EnterpriseCustomerUser.objects.filter(
                enterprise_customer=enterprise_customer,
                user_id=self.user.id,
                active=True
            ).count() == 1

    @mock.patch('enterprise.tpa_pipeline.is_multiple_user_enterprises_feature_enabled')
    def test_handle_enterprise_logistration_not_user_linking(self, multiple_enterprises_feature):
        """
        Test if there is not any enterprise customer then EnterpriseCustomerUser would not be associated with it.
        """
        backend = self.get_mocked_sso_backend()
        self.user = UserFactory()
        multiple_enterprises_feature.return_value = True
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            enterprise_customer = EnterpriseCustomerFactory(
                enable_data_sharing_consent=False
            )
            fake_get_ec.return_value = None
            assert handle_enterprise_logistration(backend, self.user) is None
            assert EnterpriseCustomerUser.objects.filter(
                enterprise_customer=enterprise_customer,
                user_id=self.user.id,
                active=True
            ).count() == 0

    def test_handle_enterprise_logistration_user_multiple_enterprises_linking(self):
        """
        Test that if user has multiple enterprise_customers then active status of latest
         enterprise_customer with which user is logged in will be marked as True and active
          status of other enterprise_customers will be marked as False.
        """
        backend = self.get_mocked_sso_backend()
        self.user = UserFactory(is_active=True)
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            enterprise_customer = EnterpriseCustomerFactory(
                enable_data_sharing_consent=False
            )
            enterprise_customer_old = EnterpriseCustomerFactory(
                enable_data_sharing_consent=False
            )
            EnterpriseCustomerUser.objects.create(
                enterprise_customer=enterprise_customer_old,
                user_id=self.user.id,
                active=True
            )
            fake_get_ec.return_value = enterprise_customer
            assert handle_enterprise_logistration(backend, self.user) is None
            assert EnterpriseCustomerUser.objects.filter(
                enterprise_customer=enterprise_customer,
                user_id=self.user.id,
                active=True
            ).count() == 1
            assert EnterpriseCustomerUser.objects.filter(
                enterprise_customer=enterprise_customer_old,
                user_id=self.user.id,
                active=False
            ).count() == 1

    @ddt.data(
        (False, True, 'facebook'),
        (True, False, 'facebook'),
        (True, False, 'facebook'),
        (False, True, 'facebook'),
        (True, True, 'google-oauth2'),
        (False, False, 'google-oauth2'),
        (False, True, 'google-oauth2'),
        (True, False, 'google-oauth2'),
    )
    @ddt.unpack
    @mock.patch('enterprise.tpa_pipeline.is_multiple_user_enterprises_feature_enabled')
    def test_social_auth_user_login_associated_with_multiple_enterprise(self,
                                                                        new_association,
                                                                        multiple_enterprise_switch,
                                                                        backend_name,
                                                                        multiple_enterprises_feature):
        """
        Test redirect to enterprise selection page, if socialAuth user has LMS attached account
        and part of multiple enterprises
        """
        kwargs = {'new_association': new_association}
        backend = self.get_mocked_sso_backend()
        backend.name = backend_name
        backend.strategy.session_get.return_value = 'not-an-enrollment-url'
        self.user = UserFactory(is_active=True)
        multiple_enterprises_feature.return_value = multiple_enterprise_switch
        enterprise_customer = EnterpriseCustomerFactory(
            enable_data_sharing_consent=False
        )
        enterprise_customer_old = EnterpriseCustomerFactory(
            enable_data_sharing_consent=False
        )
        EnterpriseCustomerUser.objects.create(
            enterprise_customer=enterprise_customer_old,
            user_id=self.user.id,
            active=False
        )
        EnterpriseCustomerUser.objects.create(
            enterprise_customer=enterprise_customer,
            user_id=self.user.id,
            active=True
        )
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            with mock.patch('enterprise.tpa_pipeline.select_enterprise_page_as_redirect_url') as ent_page_redirect:  # pylint: disable=invalid-name
                fake_get_ec.return_value = None
                handle_enterprise_logistration(backend, self.user, **kwargs)
                if new_association or not multiple_enterprise_switch:
                    ent_page_redirect.assert_not_called()
                else:
                    ent_page_redirect.called_once()

    @ddt.data(
        (False, 'facebook'),
        (False, 'google-oauth2'),
    )
    @ddt.unpack
    @mock.patch('enterprise.tpa_pipeline.is_multiple_user_enterprises_feature_enabled')
    def test_social_auth_user_login_associated_with_one_enterprise(self, new_association, backend_name,
                                                                   multiple_enterprises_feature):
        """
        Test that if socialAuth user has edx attached account and is part of one enterprises then redirection url
        is not changed
        """
        kwargs = {'new_association': new_association}
        backend = self.get_mocked_sso_backend()
        backend.name = backend_name
        backend.strategy.session_get.return_value = 'not-an-enrollment-url'
        self.user = UserFactory(is_active=True)
        multiple_enterprises_feature.return_value = True
        enterprise_customer = EnterpriseCustomerFactory(
            enable_data_sharing_consent=False
        )

        EnterpriseCustomerUser.objects.create(
            enterprise_customer=enterprise_customer,
            user_id=self.user.id,
            active=False
        )
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            with mock.patch('enterprise.tpa_pipeline.select_enterprise_page_as_redirect_url') as ent_page_redirect:  # pylint: disable=invalid-name
                fake_get_ec.return_value = None
                handle_enterprise_logistration(backend, self.user, **kwargs)
                ent_page_redirect.assert_not_called()

    @ddt.data(
        (True, False, True, 'facebook'),
        (False, False, True, 'facebook'),
        (True, True, False, 'facebook'),
        (False, True, False, 'facebook'),
        (True, True, False, 'facebook'),
        (False, True, False, 'facebook'),
        (True, False, True, 'facebook'),
        (False, False, True, 'facebook'),
        (True, True, True, 'google-oauth2'),
        (False, True, True, 'google-oauth2'),
        (True, False, False, 'google-oauth2'),
        (False, False, False, 'google-oauth2'),
        (True, False, True, 'google-oauth2'),
        (False, False, True, 'google-oauth2'),
        (True, True, False, 'google-oauth2'),
        (False, True, False, 'google-oauth2'),
    )
    @ddt.unpack
    @mock.patch('enterprise.tpa_pipeline.is_multiple_user_enterprises_feature_enabled')
    def test_bypass_enterprise_selection_page_for_enrollment_url_login(self,
                                                                       using_enrollment_url,
                                                                       new_association,
                                                                       multiple_enterprise_switch,
                                                                       backend_name,
                                                                       multiple_enterprises_feature):
        """
        Test that enterprise selection page is bypassed if socialAuth user is part of multiple enterprises
        and uses an enrollment url for login
        """
        kwargs = {'new_association': new_association}
        backend = self.get_mocked_sso_backend()
        backend.name = backend_name
        if using_enrollment_url:
            backend.strategy.session_get.return_value = '/enterprise/12e87171-fb0a/course/course-v1:Test/enroll'
        else:
            backend.strategy.session_get.return_value = 'not-an-enrollment-url'
        self.user = UserFactory(is_active=True)
        multiple_enterprises_feature.return_value = multiple_enterprise_switch
        enterprise_customer = EnterpriseCustomerFactory(
            enable_data_sharing_consent=False
        )
        enterprise_customer_old = EnterpriseCustomerFactory(
            enable_data_sharing_consent=False
        )
        EnterpriseCustomerUser.objects.create(
            enterprise_customer=enterprise_customer_old,
            user_id=self.user.id,
            active=False
        )
        EnterpriseCustomerUser.objects.create(
            enterprise_customer=enterprise_customer,
            user_id=self.user.id,
            active=True
        )
        with mock.patch('enterprise.tpa_pipeline.get_enterprise_customer_for_running_pipeline') as fake_get_ec:
            with mock.patch(
                    'enterprise.tpa_pipeline.select_enterprise_page_as_redirect_url') as ent_page_redirect:  # pylint: disable=invalid-name
                fake_get_ec.return_value = None
                handle_enterprise_logistration(backend, self.user, **kwargs)
                if new_association or not multiple_enterprise_switch or using_enrollment_url:
                    ent_page_redirect.assert_not_called()
                else:
                    ent_page_redirect.called_once()

    def test_get_ec_for_pipeline(self):
        """
        Test that we get the correct results for a given running pipeline.
        """
        with mock.patch('enterprise.tpa_pipeline.Registry') as fake_registry:
            provider = mock.MagicMock(provider_id='provider_slug')
            fake_registry.get_from_pipeline.return_value = provider
            assert get_enterprise_customer_for_running_pipeline(self.request, 'pipeline') == self.customer

            # pipeline is None
            assert get_enterprise_customer_for_running_pipeline(self.request, None) is None

            # provider_id is None
            provider = mock.MagicMock(provider_id=None)
            fake_registry.get_from_pipeline.return_value = provider
            assert get_enterprise_customer_for_running_pipeline(self.request, 'pipeline') is None
コード例 #55
0
ファイル: tests.py プロジェクト: stephengtuggy/sjvair.com
 def setUp(self):
     self.factory = RequestFactory()
コード例 #56
0
ファイル: tests.py プロジェクト: tadeoos/django-smart-lists
 def setUp(self):
     self.sample = SampleModel.objects.create(
         title='I just love django-smart-lists!', category='blog_post')
     self.factory = RequestFactory()
コード例 #57
0
ファイル: test_views.py プロジェクト: wearpants/osf.io
 def test_remove_two_factor_get(self, mock_delete_addon):
     guid = self.user._id
     request = RequestFactory().get('/fake_path')
     remove_2_factor(request, guid)
     mock_delete_addon.assert_called_with('twofactor')
コード例 #58
0
ファイル: pywb_config.py プロジェクト: chasekafei/perma
 def __init__(self, filename):
     self.filename = filename
     self.fake_request = RequestFactory(
         HTTP_HOST=settings.WARC_HOST).get('/fake')
コード例 #59
0
ファイル: test_views.py プロジェクト: wearpants/osf.io
 def setUp(self):
     self.user = UserFactory()
     self.request = RequestFactory().get('/fake_path')
コード例 #60
0
ファイル: tests.py プロジェクト: stephengtuggy/sjvair.com
class EndpointTests(TestCase):
    fixtures = ['purple-air.yaml', 'bam1022.yaml']

    def setUp(self):
        self.factory = RequestFactory()

    def get_purple_air(self):
        return PurpleAir.objects.get(data__0__ID=8892)

    def get_bam1022(self):
        return BAM1022.objects.get(name='CCAC')

    def test_monitor_detail(self):
        '''
            Test that we can GET the monitor detail endpoint.
        '''
        monitor = self.get_purple_air()
        url = reverse('api:v1:monitors:monitor-detail', kwargs={
            'monitor_id': monitor.pk
        })
        request = self.factory.get(url)
        request.monitor = monitor
        response = monitor_detail(request, monitor_id=monitor.pk)
        content = get_response_data(response)

        assert response.status_code == 200
        assert content['data']['id'] == str(monitor.pk)

    def test_monitor_list(self):
        '''
            Test that we can GET the monitor list endpoint.
        '''
        url = reverse('api:v1:monitors:monitor-list')
        request = self.factory.get(url)
        response = monitor_list(request)
        content = get_response_data(response)
        assert response.status_code == 200

    def test_entry_list(self):
        '''
            Test that we can GET the entry list endpoint.
        '''
        monitor = self.get_purple_air()
        url = reverse('api:v1:monitors:entry-list', kwargs={'monitor_id': monitor.pk})
        params = {'sensor': 'a', 'field': 'pm2_env'}
        request = self.factory.get(url, params)
        request.monitor = monitor
        response = entry_list(request, monitor_id=monitor.pk)
        content = get_response_data(response)

        sensor_count = monitor.entries.filter(sensor=params['sensor']).count()

        assert response.status_code == 200
        assert len(content['data']) == content['count'] == sensor_count
        assert set(e['sensor'] for e in content['data']) == {params['sensor']}

    def test_create_entry(self):
        '''
            Test that we can create an entry.
        '''
        monitor = self.get_bam1022()
        payload = {
            'Time': timezone.now().strftime('%Y-%m-%d %H:%M:%S'),
            'AT(C)': '30.6',
            'RH(%)': '25.0',
            'BP(mmHg)': '764.5',
            'ConcRT(ug/m3)': '24',
        }
        url = reverse('api:v1:monitors:entry-list', kwargs={'monitor_id': monitor.pk})
        request = self.factory.post(url, payload, HTTP_ACCESS_KEY=str(monitor.access_key))
        request.monitor = monitor
        response = entry_list(request, monitor_id=monitor.pk)
        content = get_response_data(response)

        assert response.status_code == 200
        assert content['data']['celcius'] == payload['AT(C)']
        assert content['data']['fahrenheit'] is not None

        entry = Entry.objects.latest('timestamp')
        assert entry.is_processed

    def test_duplicate_entry(self):
        '''
            Test that duplicate entries by timestamp are not created.
        '''
        monitor = self.get_bam1022()
        payload = {
            'Time': timezone.now(),
            'AT(C)': '30.60',
            'RH(%)': '25.00',
            'BP(mmHg)': '764.5',
            'ConcRT(ug/m3)': '24',
        }

        # Create the initial entry
        entry = monitor.create_entry(payload)
        monitor.process_entry(entry)
        entry.save()

        # Now call the API with the same payload and verify that it fails.
        url = reverse('api:v1:monitors:entry-list', kwargs={'monitor_id': monitor.pk})
        request = self.factory.post(url, payload, HTTP_ACCESS_KEY=str(monitor.access_key))
        request.monitor = monitor
        response = entry_list(request, monitor_id=monitor.pk)
        content = get_response_data(response)

        assert response.status_code == 400
        assert monitor.entries.filter(timestamp=payload['Time']).count() == 1