django.test.client.RequestFactory.get

Here are the examples of the python api django.test.client.RequestFactory.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: wiggum
Source File: test_backends.py
View license
    def test_jwt_ok(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_ok

        result = self.backend.authenticate(request)

        self.assertEqual(self.user, result)

Example 2

Project: django-allauth
Source File: tests.py
View license
    def test_email_escaping(self):
        site = get_current_site()
        site.name = '<enc&"test>'
        site.save()
        u = get_user_model().objects.create(
            username='test',
            email='[email protected]')
        request = RequestFactory().get('/')
        EmailAddress.objects.add_email(request, u, u.email, confirm=True)
        self.assertTrue(mail.outbox[0].subject[1:].startswith(site.name))

Example 3

Project: django-allauth
Source File: tests.py
View license
    def test_media_js(self):
        provider = providers.registry.by_id(FacebookProvider.id)
        request = RequestFactory().get(reverse('account_login'))
        request.session = {}
        script = provider.media_js(request)
        self.assertTrue('"appId": "app123id"' in script)

Example 4

Project: PyClassLessons
Source File: test_signals.py
View license
    def test_update_last_login(self):
        """Ensure that only `last_login` is updated in `update_last_login`"""
        user = User.objects.get(pk=3)
        old_last_login = user.last_login

        user.username = "This username shouldn't get saved"
        request = RequestFactory().get('/login')
        signals.user_logged_in.send(sender=user.__class__, request=request,
            user=user)
        user = User.objects.get(pk=3)
        self.assertEqual(user.username, 'staff')
        self.assertNotEqual(user.last_login, old_last_login)

Example 5

Project: wiggum
Source File: test_backends.py
View license
    def test_bad_jwt(self):
        request = RequestFactory().get("/something")
        request.COOKIES[settings.JWT_COOKIE_NAME] = self.jwt_wrong

        result = self.backend.authenticate(request)

        self.assertIsNone(result)

Example 6

Project: wiggum
Source File: test_middleware.py
View license
    def test_admin_url_user_not_staff(self):
        request = RequestFactory().get(reverse("admin:index"))
        request.user = self.user
        result = self.middleware.process_request(request)

        self.assertEqual(settings.ADMIN_UNATHORIZED_REDIRECTION_URL, result.url)
        self.assertTrue(isinstance(result, HttpResponseRedirect))

Example 7

Project: wiggum
Source File: test_middleware.py
View license
    def test_admin_url_user_staff(self):
        adm = User.objects.create_superuser(username="batmanadmin",
                                            email="[email protected]")
        request = RequestFactory().get(reverse("admin:index"))
        request.user = adm
        result = self.middleware.process_request(request)

        self.assertIsNone(result)

Example 8

Project: wiggum
Source File: test_middleware.py
View license
    def test_not_jwt(self):
        request = RequestFactory().get("/middleware")
        # Set no session request
        anon = AnonymousUser()
        request.user = anon
        request.session = SessionStore()

        result = self.middleware.process_request(request)
        self.assertIsNone(result)
        self.assertEqual(anon, request.user)

Example 9

Project: Misago
Source File: test_errorpages.py
View license
    def setUp(self):
        self.misago_request = RequestFactory().get(reverse('misago:index'))
        self.site_request = RequestFactory().get(reverse('raise-403'))

        self.misago_request.user = AnonymousUser()
        self.site_request.user = AnonymousUser()

        self.misago_request.include_frontend_context = True
        self.site_request.include_frontend_context = True

        self.misago_request.frontend_context = {}
        self.site_request.frontend_context = {}

Example 10

Project: Misago
Source File: test_utils.py
View license
    def test_is_request_to_misago(self):
        """
        is_request_to_misago correctly detects requests directed at Misago
        """
        misago_prefix = reverse('misago:index')

        for path in VALID_PATHS:
            request = RequestFactory().get('/')
            request.path_info = path
            self.assertTrue(
                is_request_to_misago(request),
                '"%s" is not overlapped by "%s"' % (path, misago_prefix))

        for path in INVALID_PATHS:
            request = RequestFactory().get('/')
            request.path_info = path
            self.assertFalse(
                is_request_to_misago(request),
                '"%s" is overlapped by "%s"' % (path, misago_prefix))

Example 11

Project: django-user_agents
Source File: tests.py
View license
    def test_filters(self):
        request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('')
        self.assertTrue(user_agents.is_mobile(request))
        self.assertTrue(user_agents.is_touch_capable(request))
        self.assertFalse(user_agents.is_tablet(request))
        self.assertFalse(user_agents.is_pc(request))
        self.assertFalse(user_agents.is_bot(request))

Example 12

Project: django-user_agents
Source File: tests.py
View license
    @override_settings(USER_AGENTS_CACHE=None)
    def test_disabled_cache(self):
        reload_module(utils)  # re-import with patched settings

        request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('')
        user_agent = get_user_agent(request)
        self.assertIsInstance(user_agent, UserAgent)
        self.assertIsNone(cache.get(get_cache_key(iphone_ua_string)))

Example 13

Project: django-user_agents
Source File: tests.py
View license
    @override_settings(USER_AGENTS_CACHE='test')
    def test_custom_cache(self):
        reload_module(utils)  # re-import with patched settings

        request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('')
        user_agent = get_user_agent(request)
        self.assertIsInstance(user_agent, UserAgent)
        self.assertIsNone(cache.get(get_cache_key(iphone_ua_string)))
        self.assertIsInstance(utils.cache.get(get_cache_key(iphone_ua_string)), UserAgent)

Example 14

Project: shuup
Source File: test_editor_view.py
View license
@contextmanager
def initialize_editor_view(view_name, placeholder_name, request=None):
    if request is None:
        request = RequestFactory().get("/")
    request.user = SuperUser()
    if hasattr(request.GET, "_mutable"):
        request.GET._mutable = True  # Ahem
    request.GET.update({
        "theme": FauxTheme.identifier,
        "view": view_name,
        "ph": placeholder_name
    })

    with plugin_override():
        with override_provides("xtheme", ["shuup_tests.xtheme.utils:FauxTheme"]):
            with override_current_theme_class(FauxTheme):
                yield EditorView(request=request, args=(), kwargs={})

Example 15

Project: shuup
Source File: test_editor_view.py
View license
@pytest.mark.django_db
def test_get_global_placeholder():
    request = RequestFactory().get("/")
    layout, svc = get_test_layout_and_svc()
    with initialize_editor_view(svc.view_name, layout.placeholder_name, request=request) as view_obj:
        view_name_1 = view_obj.dispatch(view_obj.request).context_data["view"].view_config.view_name
        view_obj.request.GET.update({"x": 0, "y": 0, "global_type": True})
        view_name_2 = view_obj.dispatch(view_obj.request).context_data["view"].view_config.view_name
        assert view_name_1 != view_name_2
        assert view_name_2 == XTHEME_GLOBAL_VIEW_NAME

Example 16

Project: shuup
Source File: utils.py
View license
def get_request(edit=False):
    request = RequestFactory().get("/")
    request.session = {}
    if edit:
        request.user = SuperUser()
        set_edit_mode(request, True)
        assert is_edit_mode(request)
    else:
        request.user = AnonymousUser()
    return request

Example 17

Project: splunk-webframework
Source File: signals.py
View license
    def test_update_last_login(self):
        """Ensure that only `last_login` is updated in `update_last_login`"""
        user = User.objects.get(pk=3)
        old_last_login = user.last_login

        user.username = "This username shouldn't get saved"
        request = RequestFactory().get('/login')
        signals.user_logged_in.send(sender=user.__class__, request=request,
            user=user)
        user = User.objects.get(pk=3)
        self.assertEqual(user.username, 'staff')
        self.assertNotEqual(user.last_login, old_last_login)

Example 18

Project: django-invitations
Source File: test_allauth.py
View license
    @override_settings(
        INVITATIONS_INVITATION_ONLY=True,
    )
    def test_allauth_adapter_invitations_only(self):
        signup_request = RequestFactory().get(reverse(
            'account_signup', urlconf='allauth.account.urls'))
        self.assertFalse(
            self.adapter.is_open_for_signup(signup_request))
        response = self.client.get(
            reverse('account_signup'))
        self.assertIn('Sign Up Closed', response.content.decode('utf8'))

Example 19

Project: django-invitations
Source File: tests.py
View license
    @patch('invitations.signals.invite_url_sent.send')
    def test_invite_url_sent_triggered_correctly(self, mock_signal):
        invite_url = reverse('invitations:accept-invite',
                             args=[self.invite.key])
        request = RequestFactory().get('/')
        invite_url = request.build_absolute_uri(invite_url)

        self.invite.send_invitation(request)

        self.assertTrue(mock_signal.called)
        self.assertEqual(mock_signal.call_count, 1)

        mock_signal.assert_called_with(
            instance=self.invite,
            invite_url_sent=invite_url,
            inviter=self.user,
            sender=Invitation,
        )

Example 20

Project: django-invitations
Source File: tests.py
View license
    @override_settings(
        INVITATIONS_ALLOW_JSON_INVITES=True
    )
    def test_anonymous_get(self):
        request = RequestFactory().get(
            reverse('invitations:send-json-invite'),
            content_type='application/json')
        request.user = AnonymousUser()
        response = SendJSONInvite.as_view()(request)

        self.assertEqual(response.status_code, 302)

Example 21

Project: django-invitations
Source File: tests.py
View license
    @override_settings(
        INVITATIONS_ALLOW_JSON_INVITES=True
    )
    def test_authenticated_get(self):
        request = RequestFactory().get(
            reverse('invitations:send-json-invite'),
            content_type='application/json')
        request.user = self.user
        response = SendJSONInvite.as_view()(request)

        self.assertEqual(response.status_code, 405)

Example 22

Project: djproxy
Source File: header_passthrough_tests.py
View license
    def setUp(self):
        self.proxy = TestProxy.as_view()
        self.browser_request = RequestFactory().get('/')

        # Fake headers that are representative of how Django munges them when
        # it sticks them into the META dict.
        self.browser_request.META['HTTP_Host'] = 'cnn.com'
        self.browser_request.META['HTTP_Fake_Header'] = 'header_value'
        self.browser_request.META['HTTP_X_Forwarded_For'] = 'ipaddr 1'
        self.browser_request.META['HTTP_UNNORMALIZED_HEADER'] = 'header value'
        self.browser_request.META['CONTENT_TYPE'] = 'header value'

        self.request = self.patch_request(Mock(headers={'Fake-Header': '123'}))

        self.proxy(self.browser_request)

        # The value of the headers kwarg that gets passed to request_methd
        self.headers = self.request.mock_calls[0][2]['headers']

Example 23

Project: djproxy
Source File: header_tests.py
View license
    def setUp(self):
        self.request = RequestFactory().get('/')

        # Fake headers that are representative of how Django munges them when
        # it sticks them into the META dict.
        self.request.META['HTTP_Host'] = 'cnn.com'
        self.request.META['HTTP_Fake_Header'] = 'header_value'
        self.request.META['HTTP_X_Forwarded_For'] = 'ipaddr 1'
        self.request.META['HTTP_UNNORMALIZED_HEADER'] = 'header value'
        self.request.META['CONTENT_TYPE'] = 'header value'

        self.headers = HeaderDict.from_request(self.request)

Example 24

Project: djproxy
Source File: view_configuration_tests.py
View license
    def setUp(self):
        TestProxy.pass_query_string = False
        self.fake_request = RequestFactory().get('/yay/?yay=foo,bar')
        self.proxy = TestProxy.as_view()

        self.request = self.patch_request(
            Mock(raw='', status_code=200, headers={}))

        self.proxy(self.fake_request, url='yay/')

Example 25

Project: djproxy
Source File: view_configuration_tests.py
View license
    def setUp(self):
        self.fake_request = RequestFactory().get('/')
        self.proxy = TestProxy.as_view()

        self.request = self.patch_request(
            Mock(raw='', status_code=200, headers={}))

        self.proxy(self.fake_request, url='yay/')

Example 26

Project: djproxy
Source File: view_configuration_tests.py
View license
    def setUp(self):
        self.fake_request = RequestFactory().get('/')
        self.proxy = UnverifiedSSLProxy.as_view()

        self.request = self.patch_request(
            Mock(raw='', status_code=200, headers={}))

        self.proxy(self.fake_request, url='yay/')

Example 27

Project: djproxy
Source File: view_configuration_tests.py
View license
    def setUp(self):
        self.fake_request = RequestFactory().get('/')
        self.proxy = SpecifiedCertProxy.as_view()

        self.request = self.patch_request(
            Mock(raw='', status_code=200, headers={}))

        self.proxy(self.fake_request, url='yay/')

Example 28

Project: django-subdomains
Source File: tests.py
View license
    def test_subdomain_attribute(self):
        def subdomain(subdomain):
            """
            Returns the subdomain associated with the request by the middleware
            for the given subdomain.
            """
            host = self.get_host_for_subdomain(subdomain)
            request = RequestFactory().get('/', HTTP_HOST=host)
            self.middleware.process_request(request)
            return request.subdomain

        self.assertEqual(subdomain(None), None)
        self.assertEqual(subdomain('www'), 'www')
        self.assertEqual(subdomain('www.subdomain'), 'www.subdomain')
        self.assertEqual(subdomain('subdomain'), 'subdomain')
        self.assertEqual(subdomain('another.subdomain'), 'another.subdomain')

Example 29

Project: django-subdomains
Source File: tests.py
View license
    def test_case_insensitive_subdomain(self):
        host = 'WWW.%s' % self.DOMAIN
        request = RequestFactory().get('/', HTTP_HOST=host)
        self.middleware.process_request(request)
        self.assertEqual(request.subdomain, 'www')

        host = 'www.%s' % self.DOMAIN.upper()
        request = RequestFactory().get('/', HTTP_HOST=host)
        self.middleware.process_request(request)
        self.assertEqual(request.subdomain, 'www')

Example 30

Project: django-subdomains
Source File: tests.py
View license
    def test_url_routing(self):
        def urlconf(subdomain):
            """
            Returns the URLconf associated with this request.
            """
            host = self.get_host_for_subdomain(subdomain)
            request = RequestFactory().get('/', HTTP_HOST=host)
            self.middleware.process_request(request)
            return getattr(request, 'urlconf', None)

        self.assertEqual(urlconf(None), self.get_path_to_urlconf('marketing'))
        self.assertEqual(urlconf('www'), self.get_path_to_urlconf('marketing'))
        self.assertEqual(urlconf('api'), self.get_path_to_urlconf('api'))

        # Falls through to the actual ROOT_URLCONF.
        self.assertEqual(urlconf('subdomain'), None)

Example 31

Project: mysqlapi
Source File: test_bind.py
View license
    def test_bind_app_should_accept_only_post_and_delete(self):
        request = RequestFactory().get("/")
        response = BindApp.as_view()(request, "name")
        self.assertEqual(405, response.status_code)
        request = RequestFactory().put("/")
        response = BindApp.as_view()(request, "name")
        self.assertEqual(405, response.status_code)

Example 32

Project: mysqlapi
Source File: test_healthcheck.py
View license
    def test_healthcheck_returns_204_if_the_mysql_server_is_on(self):
        request = RequestFactory().get("/resources/g8mysql/status/")
        with mock.patch("mysqlapi.api.models.DatabaseManager.is_up") as is_up:
            is_up.return_value = True
            view = Healthcheck()
            fake = mocks.FakeEC2Client()
            view._client = fake
            response = view.get(request, "g8mysql")
        self.assertEqual(204, response.status_code)

Example 33

Project: mysqlapi
Source File: test_healthcheck.py
View license
    def test_healthcheck_returns_500_if_the_mysql_server_is_off(self):
        request = RequestFactory().get("/resources/g8mysql/status/")
        with mock.patch("mysqlapi.api.models.DatabaseManager.is_up") as is_up:
            is_up.return_value = False
            view = Healthcheck()
            fake = mocks.FakeEC2Client()
            view._client = fake
            response = view.get(request, "g8mysql")
        self.assertEqual(500, response.status_code)

Example 34

Project: mysqlapi
Source File: test_healthcheck.py
View license
    def test_healthcheck_returns_201_when_ec2_instance_is_running(self):
        request = RequestFactory().get("/resources/g8mysql/status/")
        with mock.patch("mysqlapi.api.models.DatabaseManager.is_up") as is_up:
            is_up.return_value = True
            view = Healthcheck()
            fake = mocks.FakeEC2Client()
            view._client = fake
            response = view.get(request, "g8mysql")
        self.assertEqual(204, response.status_code)

Example 35

Project: mysqlapi
Source File: test_healthcheck.py
View license
    def test_healthcheck_doesnt_touch_ec2_when_instance_is_pending(self):
        self.instance.state = "pending"
        self.instance.save()
        request = RequestFactory().get("/resources/g8mysql/status/")
        view = Healthcheck()
        fake = mocks.FakeEC2ClientPendingInstance()
        view._client = fake

        response = view.get(request, "g8mysql")
        self.assertEqual(202, response.status_code)
        self.assertEqual([], fake.actions)

Example 36

Project: vegphilly.com
Source File: admin_views.py
View license
    def test_pending_approval_count_all_approved(self):
        Vendor.objects.create(name="Test Vendor",
                              approval_status=SF.APPROVED)
        request = RequestFactory().get('')
        request.user = get_user(is_staff=True)
        response = pending_approval_count(request)
        self.assertEqual(response.content, "0")

Example 37

Project: vegphilly.com
Source File: admin_views.py
View license
    def test_pending_approval_count_with_pending(self):
        Vendor.objects.create(name="Test Vendor")
        request = RequestFactory().get('')
        request.user = get_user(is_staff=True)
        response = pending_approval_count(request)
        self.assertEqual(response.content, "1")

Example 38

Project: django-knowledge
Source File: templatetags.py
View license
    def test_page_query(self):
        request = RequestFactory().get('/faker/?something=extra&page=123')
        self.assertEquals('something=extra&amp;page=666', page_query(request, 666))

        request = RequestFactory().get('/faker/?something=extra')
        self.assertEquals('something=extra&amp;page=666', page_query(request, 666))

Example 39

Project: OIPA
Source File: test_together_filterset.py
View license
    def test_filter_is_applied_together(self):
        """
        Test when specifying together_exclusive, the filters are applied together
        """

        request = RequestFactory().get('/api/activities/?budget_period_start=2015-04-01&budget_period_end=2016-03-31')
        query_params = request.GET

        queryset = Activity.objects.all()

        resulting_qs = TestFilter(query_params, queryset=queryset).qs

        query = resulting_qs.query

        # only the main table and the budget table are joined
        self.assertEqual(len(query.__dict__['alias_map']), 2)

Example 40

Project: OIPA
Source File: test_together_filterset.py
View license
    def test_without_together_exclusive(self):
        request = RequestFactory().get('/api/activities/?budget_period_start=2015-04-01&budget_period_end=2016-03-31')
        query_params = request.GET

        queryset = Activity.objects.all()

        resulting_qs = TestWithoutFilter(query_params, queryset=queryset).qs
        query = resulting_qs.query

        # table joined twice, hence 3 aliases
        self.assertEqual(len(query.__dict__['alias_map']), 3)

Example 41

View license
    def setUp(self):
        # create context mock
        request = RequestFactory().get('/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        request.session.save()
        self.context = RequestContext(request)
        self.plugin = mixer.blend('image_gallery.GalleryPlugin')
        self.cmsplugin = CMSGalleryPlugin()

Example 42

View license
    def setUp(self):
        # create context mock
        request = RequestFactory().get('/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        request.session.save()
        self.context = RequestContext(request)
        self.gallery = mixer.blend('image_gallery.Gallery', is_published=True,
                                   folder=mixer.blend('filer.Folder'))

Example 43

View license
    def test_render_tag(self):
        request = RequestFactory().get('/')
        t = Template('{% load position_tags %}{% position_result_list cl %}')
        change_list = ChangeList(
            request=request, model=DummyModel, list_display=['name'],
            list_display_links=None, list_filter=None, date_hierarchy=None,
            search_fields=None, list_select_related=None, list_per_page=100,
            list_max_show_all=10, list_editable=None,
            model_admin=GenericPositionsAdmin(DummyModel, AdminSite()))
        change_list.formset = None
        c = Context({'cl': change_list})
        self.assertIn('name="position-{0}"'.format(self.first_model.id),
                      t.render(c))

Example 44

Project: django-libs
Source File: views_mixins_tests.py
View license
    def test_mixin(self):
        """Test for the ``AjaxResponseMixin`` class."""
        extra = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
        req = RequestFactory().get('/', **extra)
        self.view.request = req
        self.assertEqual(self.view.get_template_names(),
                         ['ajax_test_template.html'],
                         msg='Got the wrong template name.')

Example 45

View license
    def test_tag(self):
        activate('en')
        req = RequestFactory().get('/')
        context = {'request': req, }
        result = get_recent_news(context)
        self.assertEqual(result.count(), 3, msg=(
            'Should return last three recent news'))
        result = get_recent_news(context, category='foo')
        self.assertEqual(result.count(), 3, msg=(
            'Should return last three recent news, if category is invalid.'))
        result = get_recent_news(context, category=self.category.slug)
        self.assertEqual(result.count(), 1, msg=(
            'Should only return recent news from chosen category'))
        self.news_entry2.categories.add(self.category)
        result = get_recent_news(context, category=self.category.slug)
        self.assertEqual(result.count(), 2, msg=(
            'Should only return recent news from chosen category'))

Example 46

Project: django-object-events
Source File: tags_tests.py
View license
    def test_tag(self):
        # create context mock
        request = RequestFactory().get('/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        request.session.save()
        context = RequestContext(request)

        # Returns empty dict if there is no authenticated user
        self.assertEqual(render_notifications(context), '\n')

        # Returns notifications.html
        request.user = UserFactory()
        ObjectEventFactory(user=request.user)
        self.assertTrue(render_notifications(context))

Example 47

Project: django-crumbs
Source File: tests.py
View license
    def test_add_name_no_args(self):
        template = Template("{% load breadcrumb_tags %}{% add_crumb 'List' 'list_view' %}")
        request = RequestFactory().get('/')
        context = RequestContext(request)
        result = template.render(context)
        self.assertEqual(result, '')
        self.assertEqual(request.breadcrumbs, [('List', '/list_view/')])

Example 48

Project: django-crumbs
Source File: tests.py
View license
    def test_add_absolute_no_args(self):
        template = Template("{% load breadcrumb_tags %}{% add_crumb 'Home' '/home/' %}")
        request = RequestFactory().get('/')
        context = RequestContext(request)
        result = template.render(context)
        self.assertEqual(result, '')
        self.assertEqual(request.breadcrumbs, [('Home', '/home/')])

Example 49

Project: django-crumbs
Source File: tests.py
View license
    def test_add_kwargs(self):
        template = Template("{% load breadcrumb_tags %}{% add_crumb crumb='Home' url='/home/' %}")
        request = RequestFactory().get('/')
        context = RequestContext(request)
        result = template.render(context)
        self.assertEqual(result, '')
        self.assertEqual(request.breadcrumbs, [('Home', '/home/')])

Example 50

Project: django-crumbs
Source File: tests.py
View license
    def test_add_with_args(self):
        template = Template("{% load breadcrumb_tags %}{% add_crumb 'Details' 'detail_view' 44 %}")
        request = RequestFactory().get('/')
        context = RequestContext(request)
        result = template.render(context)
        self.assertEqual(result, '')
        self.assertEqual(request.breadcrumbs, [('Details', '/detail_view/44/')])