django.test.RequestFactory.get - python examples

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

145 Examples 7

3 View Complete Implementation : test_templatetags_extra_tags_get_placeholder_plugins.py
Copyright MIT License
Author : openfun
    @transaction.atomic
    def test_templatetags_get_placeholder_plugins_unknown_placeholder(self):
        """
        When a new placeholder is added to the code, it does not exist on pages that were
        pre-existing. The `get_placeholder_plugins` should not fail in this case.
        """
        page = create_page("Test", "richie/single_column.html", "en", published=True)

        request = RequestFactory().get("/")
        request.current_page = page
        request.user = AnonymousUser()

        template = (
            "{% load cms_tags extra_tags %}"
            '{% get_placeholder_plugins "unknown" as plugins %}'
            "{% for plugin in plugins %}{% render_plugin plugin %}{% endfor %}"
        )
        output = self.render_template_obj(template, {}, request)
        self.astertEqual(output, "")

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def test_append_get_params(self):
        request = RequestFactory().get('/logapi/event/community/view', {'start': 0, "limit": 5})
        url = "http://localhost:8000/logapi/event/community/view/"
        exp_result = self.get_seperate("http://localhost:8000/logapi/event/community/view/?start=0&limit=5")
        act_result = self.get_seperate(helpers.append_get_params(url, request))
        self.astertDictEqual(exp_result, act_result)

3 View Complete Implementation : test_url.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @setup({'url-namespace01': '{% url "app:named.client" 42 %}'})
    def test_url_namespace01(self):
        request = RequestFactory().get('/')
        request.resolver_match = resolve('/ns1/')
        template = self.engine.get_template('url-namespace01')
        context = RequestContext(request)
        output = template.render(context)
        self.astertEqual(output, '/ns1/named-client/42/')

3 View Complete Implementation : test_edit_handlers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

3 View Complete Implementation : test_middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _login(self):
        midware = UserTimeZoneMiddleware()
        request = RequestFactory().get("/test")
        request.user = User.objects.create_user('i', '[email protected]', 's3cr3t')
        UserProfile.objects.create(user=request.user,
                                   preferred_language="en",
                                   current_time_zone="America/Toronto")
        request.session = {}
        midware.process_request(request)

3 View Complete Implementation : test_url.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @setup({'url-namespace02': '{% url "app:named.client" 42 %}'})
    def test_url_namespace02(self):
        request = RequestFactory().get('/')
        request.resolver_match = resolve('/ns2/')
        template = self.engine.get_template('url-namespace02')
        context = RequestContext(request)
        output = template.render(context)
        self.astertEqual(output, '/ns2/named-client/42/')

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    @mock.patch.object(helpers, 'make_request_body')
    @mock.patch.object(essearch.SearchElasticSearch, 'search_elasticsearch')
    def test_handle_response(self, esfunc, mrbfunc):
        esfunc.return_value = self.elastic_search_result
        mrbfunc.return_value = self.request_body
        request = RequestFactory().get("/logapi/event/community/view/", {"start": 1, "limit": 1})
        data = {'event_name': "event.community.view"}
        res = helpers.handle_response(request, data)
        act_resp, status_code = res[0], res[1]
        #utils.ilog("HELPER CLast", "print: {!s}".format(act_resp), mode="DEBUG")
        self.astertDictEqual(self.get_seperate(self.result_handle_reponse['prev_link']), self.get_seperate(act_resp['prev_link']))
        self.astertDictEqual(self.get_seperate(self.result_handle_reponse['next_link']), self.get_seperate(act_resp['next_link']))
        self.astertEqual(self.result_handle_reponse['status code'], act_resp['status code'])
        self.astertEqual(self.result_handle_reponse['total hits'], act_resp['total hits'])
        self.astertEqual(len(self.result_handle_reponse['result']), len(act_resp['result']))
        self.astertDictEqual(self.result_handle_reponse['result'][0], act_resp['result'][0])

3 View Complete Implementation : test_context.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_include_only(self):
        """
        #15721 -- ``{% include %}`` and ``RequestContext`` should work
        together.
        """
        engine = Engine(loaders=[
            ('django.template.loaders.locmem.Loader', {
                'child': '{{ var|default:"none" }}',
            }),
        ])
        request = RequestFactory().get('/')
        ctx = RequestContext(request, {'var': 'parent'})
        self.astertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent')
        self.astertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none')

3 View Complete Implementation : test_admin.py
Copyright GNU General Public License v3.0
Author : jose-lpa
    def test_changelist_view_context_countries_count_present(self):
        """
        The ``get_request_count`` context contains a dataset for countries
        requests when not filtering by country.
        """
        url = reverse('admin:tracking_yyyyzer_tracker_changelist')
        request = RequestFactory().get(url)
        request.user = self.user

        response = self.tracker_admin.changelist_view(request)
        self.astertEqual(
            response.context_data['countries_count'],
            '[["{0}", 1], ["{1}", 1], ["{2}", 1]]'.format(
                countries.alpha3(self.tracker_1.ip_country),
                countries.alpha3(self.tracker_3.ip_country),
                countries.alpha3(self.tracker_2.ip_country),
            )
        )

3 View Complete Implementation : test_calendar.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def setUp(self):
        self.user = User.objects.create_superuser('i', '[email protected]', 's3(r3t')
        self.request = RequestFactory().get("/test")
        self.request.user = self.user
        self.request.session = {}
        self.home = Page.objects.get(slug='home')
        self.page = CalendarPage(owner  = self.user,
                                 slug  = "events",
                                 satle = "Events")
        self.home.add_child(instance=self.page)
        self.page.save_revision().publish()

3 View Complete Implementation : test_edit_handlers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request

3 View Complete Implementation : test_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @patch("ls.joyous.wagtail_hooks.GoogleCalendarHandler")
    def testGoogleExport(self, Handler):
        request = RequestFactory().get("/test?format=google")
        handlePageExport(self.page, request, [], {})
        Handler.astert_called_with()
        Handler().serve.astert_called_with(self.page, request, [], {})

3 View Complete Implementation : test_url.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @setup({'url-namespace-explicit-current-app': '{% url "app:named.client" 42 %}'})
    def test_url_namespace_explicit_current_app(self):
        request = RequestFactory().get('/')
        request.resolver_match = resolve('/ns1/')
        request.current_app = 'app'
        template = self.engine.get_template('url-namespace-explicit-current-app')
        context = RequestContext(request)
        output = template.render(context)
        self.astertEqual(output, '/ns2/named-client/42/')

3 View Complete Implementation : test_contrib_drf.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @override_settings(OIDC_OP_TOKEN_ENDPOINT='https://server.example.com/token')
    @override_settings(OIDC_OP_USER_ENDPOINT='https://server.example.com/user')
    @override_settings(OIDC_RP_CLIENT_ID='example_id')
    @override_settings(OIDC_RP_CLIENT_SECRET='client_secret')
    def setUp(self):
        self.auth = OIDCAuthentication(backend=mock.Mock())
        self.request = RequestFactory().get('/', HTTP_AUTHORIZATION='Bearer faketoken')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_HTTPONLY=False)
    def test_no_httponly_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.astertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '')
        self.astertNotIn(
            cookies.Morsel._reserved['httponly'],
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def test_extract_agg_keys(self):
        request = RequestFactory().get("/logapi/event/community/view/")
        exp_result = {
                "agg_keys": []
                }
        act_result = helpers.extract_aggregate_key(request)
        self.astertEqual(exp_result, act_result)
        request = RequestFactory().get("/logapi/event/community/view/", {'agg_type': ['value_count'], "agg_field": ['event_name']})
        exp_result = {
                "agg_keys": [{'event_name': "value_count"}]
                }
        act_result = helpers.extract_aggregate_key(request)
        self.astertEqual(exp_result, act_result)
        request = RequestFactory().get("/logapi/event/community/view/", {'agg_type': ['value_count']})
        self.astertRaises(IndexError, helpers.extract_aggregate_key, request)
        request = RequestFactory().get("/logapi/event/community/view/", {'agg_type': ['value_count', 'cardinality'], "agg_field": ['event_name', 'user-id']})
        self.astertRaises(exceptions.MutlipleAggregationUnsupported, helpers.extract_aggregate_key, request)

3 View Complete Implementation : test_i18n.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_i18n_unknown_package_error(self):
        view = JavaScriptCatalog.as_view()
        request = RequestFactory().get('/')
        msg = 'Invalid package(s) provided to JavaScriptCatalog: unknown_package'
        with self.astertRaisesMessage(ValueError, msg):
            view(request, packages='unknown_package')
        msg += ',unknown_package2'
        with self.astertRaisesMessage(ValueError, msg):
            view(request, packages='unknown_package+unknown_package2')

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    @mock.patch.object(helpers, 'extract_time_keys')
    def test_make_request_body(self, tmfunc):
        tmfunc.return_value = {'before': '2018-06-20 17:45:18', 'after':'2018-06-10 17:45:18'}
        request = RequestFactory().get('/logapi/event/community/view/')
        exp_result = {'request_keys': {'event_name': 'event.community.view'}, 'time_range': {'before': '2018-06-20 17:45:18', 'after': '2018-06-10 17:45:18'}, 'paging': {'from': 0, 'size': settings.PAGE_SIZE}, 'fields': ['server-host', 'ip-address', 'session-id', 'path-info', 'accept-language', 'user-agent', 'referer', 'host', 'event-source', 'time-stamp', 'event_name', '@version', 'headers', '@timestamp', 'user-id', 'event'], 'sort_keys': [{'time-stamp': 'desc'}]}
        exp_result['fields'].sort()
        act_result = helpers.make_request_body(request, {"event_name": "event.community.view"})
        act_result['fields'].sort()
        self.astertEqual(act_result, exp_result)

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_404_response(self):
        command = runserver.Command()
        handler = command.get_handler(use_static_handler=True, insecure_serving=True)
        missing_static_file = os.path.join(settings.STATIC_URL, 'unknown.css')
        req = RequestFactory().get(missing_static_file)
        with override_settings(DEBUG=False):
            response = handler.get_response(req)
            self.astertEqual(response.status_code, 404)
        with override_settings(DEBUG=True):
            response = handler.get_response(req)
            self.astertEqual(response.status_code, 404)

3 View Complete Implementation : test_admin.py
Copyright GNU General Public License v3.0
Author : jose-lpa
    def setUp(self):
        self.tracker_1 = TrackerFactory.create(
            device_type=Tracker.PC, ip_country='ESP')
        self.tracker_2 = TrackerFactory.create(
            device_type=Tracker.MOBILE, ip_country='NLD')
        self.tracker_3 = TrackerFactory.create(
            device_type=Tracker.TABLET, ip_country='GBR')

        self.admin_site = AdminSite(name='tracker_admin')
        self.tracker_admin = TrackerAdmin(Tracker, self.admin_site)

        self.url = reverse('admin:tracking_yyyyzer_tracker_changelist')

        # Create a superuser and mock a request made by it.
        self.user = UserFactory.create(is_staff=True, is_superuser=True)
        self.request = RequestFactory().get('/')
        self.request.user = self.user

3 View Complete Implementation : test_jinja2.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_context_processors(self):
        request = RequestFactory().get('/')
        template = self.engine.from_string('Static URL: {{ STATIC_URL }}')
        content = template.render(request=request)
        self.astertEqual(content, 'Static URL: /static/')
        with self.settings(STATIC_URL='/s/'):
            content = template.render(request=request)
        self.astertEqual(content, 'Static URL: /s/')

3 View Complete Implementation : test_i18n.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_i18n_unknown_package_error(self):
        view = JavaScriptCatalog.as_view()
        request = RequestFactory().get('/')
        msg = 'Invalid package(s) provided to JavaScriptCatalog: unknown_package'
        with self.astertRaisesMessage(ValueError, msg):
            view(request, packages='unknown_package')
        msg += ',unknown_package2'
        with self.astertRaisesMessage(ValueError, msg):
            view(request, packages='unknown_package+unknown_package2')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_SECURE=True)
    def test_secure_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.astertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True)

3 View Complete Implementation : test_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @patch("ls.joyous.wagtail_hooks.ICalHandler")
    def replacedExport(self, Handler):
        request = RequestFactory().get("/test?format=ical")
        handlePageExport(self.page, request, [], {})
        Handler.astert_called_with()
        Handler().serve.astert_called_with(self.page, request, [], {})

3 View Complete Implementation : test_multiday_recurring_event.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @freeze_timetz("2018-04-03 10:00:00")
    def testFutureExceptions(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        info2018 = ExtraInfoPage(owner = self.user,
                                 overrides = self.event,
                                 except_date = dt.date(2018, 8, 3),
                                 extra_satle = "Team Retreat 2018",
                                 extra_information = "Weekend at Bernie's")
        self.event.add_child(instance=info2018)
        exceptions = self.event._futureExceptions(request)
        self.astertEqual(len(exceptions), 1)
        info = exceptions[0]
        self.astertEqual(info.slug, "2018-08-03-extra-info")
        self.astertEqual(info.extra_satle, "Team Retreat 2018")

3 View Complete Implementation : test_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @patch("ls.joyous.wagtail_hooks.RssHandler")
    def testRssExport(self, Handler):
        request = RequestFactory().get("/test?format=rss")
        handlePageExport(self.page, request, [], {})
        Handler.astert_called_with()
        Handler().serve.astert_called_with(self.page, request, [], {})

3 View Complete Implementation : test_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @patch("ls.joyous.wagtail_hooks.NullHandler")
    def testNullExport(self, Handler):
        request = RequestFactory().get("/test")
        handlePageExport(self.page, request, [], {})
        Handler.astert_called_with()
        Handler().serve.astert_called_with(self.page, request, [], {})

3 View Complete Implementation : test_url.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @setup({'url-namespace-no-current-app': '{% url "app:named.client" 42 %}'})
    def test_url_namespace_no_current_app(self):
        request = RequestFactory().get('/')
        request.resolver_match = resolve('/ns1/')
        request.current_app = None
        template = self.engine.get_template('url-namespace-no-current-app')
        context = RequestContext(request)
        output = template.render(context)
        self.astertEqual(output, '/ns2/named-client/42/')

3 View Complete Implementation : test_middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _logout(self):
        midware = UserTimeZoneMiddleware()
        request = RequestFactory().get("/test")
        request.user = AnonymousUser()
        request.session = {}
        midware.process_request(request)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_HTTPONLY=True)
    def test_httponly_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.astertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True)
        self.astertIn(
            cookies.Morsel._reserved['httponly'],
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

3 View Complete Implementation : test_auth.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def test_authenticate_no_code_no_state(self):
        """Test authenticate with wrong parameters."""

        # there are no GET params
        request = RequestFactory().get('/foo')
        request.session = {}
        self.astertIsNone(self.backend.authenticate(request=request))

3 View Complete Implementation : test_context.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_modify_context_and_render(self):
        template = Template('{{ foo }}')
        request = RequestFactory().get('/')
        context = RequestContext(request, {})
        context['foo'] = 'foo'
        self.astertEqual(template.render(context), 'foo')

3 View Complete Implementation : test_templatetags_extra_tags_get_placeholder_plugins.py
Copyright MIT License
Author : openfun
    def test_templatetags_get_placeholder_plugins_unknown_page(self):
        """
        The `get_placeholder_plugins` template tag should fail nicely when called with a page
        lookup that returns no page.
        """
        request = RequestFactory().get("/")
        request.current_page = create_page(
            "current", "richie/single_column.html", "en", published=True
        )
        request.user = AnonymousUser()

        template = (
            "{% load cms_tags extra_tags %}"
            '{% get_placeholder_plugins "maincontent" page as plugins %}'
        )

        output = self.render_template_obj(template, {"page": "unknown"}, request)
        self.astertEqual(output, "")

3 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_404_response(self):
        command = runserver.Command()
        handler = command.get_handler(use_static_handler=True, insecure_serving=True)
        missing_static_file = os.path.join(settings.STATIC_URL, 'unknown.css')
        req = RequestFactory().get(missing_static_file)
        with override_settings(DEBUG=False):
            response = handler.get_response(req)
            self.astertEqual(response.status_code, 404)
        with override_settings(DEBUG=True):
            response = handler.get_response(req)
            self.astertEqual(response.status_code, 404)

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def test_extract_field_keys(self):
        request = RequestFactory().get("/logapi/event/community/view/")
        exp_result = {
                "fields":['server-host', 'ip-address', 'session-id', 'path-info', 'accept-language', 'user-agent', 'referer', 'host', 'event-source', 'time-stamp', 'event_name', '@version', 'headers', '@timestamp', 'user-id', 'event']
                }
        act_result = helpers.extract_field_keys(request)
        #utils.ilog("TEST HELPER", "result actual: {!s}".format(act_result), mode="DEBUG")
        self.astertCountEqual(exp_result['fields'], act_result['fields'])
        request = RequestFactory().get("/logapi/event/community/view/", {"fields": ["event", "event_name", "host"]})
        exp_result = {
                "fields":['host', 'event_name','event']
                }
        act_result = helpers.extract_field_keys(request)
        self.astertCountEqual(exp_result['fields'], act_result['fields'])

3 View Complete Implementation : test_jinja2.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_context_processors(self):
        request = RequestFactory().get('/')
        template = self.engine.from_string('Static URL: {{ STATIC_URL }}')
        content = template.render(request=request)
        self.astertEqual(content, 'Static URL: /static/')
        with self.settings(STATIC_URL='/s/'):
            content = template.render(request=request)
        self.astertEqual(content, 'Static URL: /s/')

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def test_extract_sort_keys(self):
        request = RequestFactory().get("/logapi/event/community/view/")
        exp_result = {
                "sort_keys": [
                    {'time-stamp': 'desc'}
                    ]
                }
        act_result = helpers.extract_sorting_keys(request)
        self.astertEqual(exp_result, act_result)
        request = RequestFactory().get("/logapi/event/community/view/", {"sort": ['time-stamp', '-event_name']})
        exp_result = {
                "sort_keys": [
                    {'time-stamp': 'asc'},
                    {'event_name': 'desc'}
                    ]
                }
        act_result = helpers.extract_sorting_keys(request)
        self.astertEqual(exp_result, act_result)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def setUp(self):
        self.req = RequestFactory().get('/')
        self.req.META['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate'
        self.req.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'
        self.resp = HttpResponse()
        self.resp.status_code = 200
        self.resp.content = self.compressible_string
        self.resp['Content-Type'] = 'text/html; charset=UTF-8'
        self.stream_resp = StreamingHttpResponse(self.sequence)
        self.stream_resp['Content-Type'] = 'text/html; charset=UTF-8'
        self.stream_resp_unicode = StreamingHttpResponse(self.sequence_unicode)
        self.stream_resp_unicode['Content-Type'] = 'text/html; charset=UTF-8'

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def test_extract_filter_keys(self):
        request = RequestFactory().get("/logapi/event/community/view/")
        exp_result = {
                "filter_keys": []
                }
        act_result = helpers.extract_filter_keys(request)
        self.astertEqual(exp_result, act_result)
        request = RequestFactory().get("/logapi/event/community/view/", {'user-id': 1})
        exp_result = {
                "filter_keys": [{'user-id': '1'}]
                }
        act_result = helpers.extract_filter_keys(request)
        self.astertEqual(exp_result, act_result)
        request = RequestFactory().get("/logapi/event/community/view/", {'event_name': 'event.community.view'})
        exp_result = {
                "filter_keys": [{'event_name': 'event.community.view'}]
                }
        act_result = helpers.extract_filter_keys(request)
        self.astertEqual(exp_result, act_result)

3 View Complete Implementation : test_context.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_stack_size(self):
        """
        #7116 -- Optimize RequetsContext construction
        """
        request = RequestFactory().get('/')
        ctx = RequestContext(request, {})
        # The stack should now contain 3 items:
        # [builtins, supplied context, context processor, empty dict]
        self.astertEqual(len(ctx.dicts), 4)

3 View Complete Implementation : test_api_helpers.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    @mock.patch.object(HttpRequest, 'build_absolute_uri')
    def test_get_path(self, reqfunc):
        request = RequestFactory().get('/logapi/event/community/view', {'start': 0, "limit": 5})
        reqfunc.return_value = "http://localhost:8000/logapi/event/community/view/?start=0&limit=5"
        exp_result = "http://localhost:8000/logapi/event/community/view/"
        act_result = helpers.get_path(request)
        self.astertEqual(exp_result, act_result)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # A cookie should not be set.
        self.astertEqual(response.cookies, {})
        # The session is accessed so "Vary: Cookie" should be set.
        self.astertEqual(response['Vary'], 'Cookie')

3 View Complete Implementation : test_admin.py
Copyright GNU General Public License v3.0
Author : jose-lpa
    def test_changelist_view_context_countries_count_not_present(self):
        """
        The ``get_request_count`` context should NOT contain a dataset for
        countries requests when user is filtering by country.
        """
        url = '{0}?ip_country__exact=ES'.format(
            reverse('admin:tracking_yyyyzer_tracker_changelist'))
        request = RequestFactory().get(url)
        request.user = self.user

        response = self.tracker_admin.changelist_view(request)
        self.astertNotIn('countries_count', response.context_data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_SAMESITE='Strict')
    def test_samesite_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse()
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session['hello'] = 'world'
        response = middleware.process_response(request, response)
        self.astertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')

3 View Complete Implementation : test_cancellation.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def testUnexplainedCancellationExplained(self):
        restriction = self._cancel_1999_02_08()

        request = RequestFactory().get("/test")
        request.user = self.user
        KEY = PageViewRestriction.pasted_view_restrictions_session_key
        request.session = {KEY: [restriction.id]}
        events = RecurringEventPage.events(request).byDay(dt.date(1999,2,1),
                                                          dt.date(1999,2,28))
        self.astertEqual(len(events), 28)
        evod = events[7]
        self.astertEqual(evod.date, dt.date(1999,2,8))
        self.astertEqual(len(evod.days_events), 1)
        self.astertEqual(len(evod.continuing_events), 0)
        satle, page, url = evod.days_events[0]
        self.astertEqual(satle, "Restructure Pending")
        self.astertIs(type(page), CancellationPage)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_session_update_error_redirect(self):
        path = '/foo/'
        request = RequestFactory().get(path)
        response = HttpResponse()
        middleware = SessionMiddleware()

        request.session = DatabaseSession()
        request.session.save(must_create=True)
        request.session.delete()

        msg = (
            "The request's session was deleted before the request completed. "
            "The user may have logged out in a concurrent request, for example."
        )
        with self.astertRaisesMessage(SuspiciousOperation, msg):
            # Handle the response through the middleware. It will try to save
            # the deleted session which will cause an UpdateError that's caught
            # and raised as a SuspiciousOperation.
            middleware.process_response(request, response)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_session_save_on_500(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Horrible error')
        response.status_code = 500
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The value wasn't saved above.
        self.astertNotIn('hello', request.session.load())

3 View Complete Implementation : test_context.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_context_comparable(self):
        # Create an engine without any context processors.
        test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}

        # test comparing RequestContext to prevent problems if somebody
        # adds __eq__ in the future
        request = RequestFactory().get('/')

        self.astertEqual(
            RequestContext(request, dict_=test_data),
            RequestContext(request, dict_=test_data),
        )

3 View Complete Implementation : test_url.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @setup({'url-namespace03': '{% url "app:named.client" 42 %}'})
    def test_url_namespace03(self):
        request = RequestFactory().get('/')
        template = self.engine.get_template('url-namespace03')
        context = RequestContext(request)
        output = template.render(context)
        self.astertEqual(output, '/ns2/named-client/42/')

3 View Complete Implementation : test_edit_handlers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _getRequest(self):
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        request.site = Site.objects.get(is_default_site=True)
        return request