Python django.test.client.RequestFactory() Examples

The following are 30 code examples for showing how to use django.test.client.RequestFactory(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.test.client , or try the search function .

Example 1
Project: django-usersettings2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def setUp(self):
        Site.objects.get_or_create(id=settings.SITE_ID, domain='example.com', name='example.com')
        self.obj = get_usersettings_model().objects.create(**self.usersettings_data)
        self.user = get_user_model().objects.create_superuser(
            self.username, self.email, self.password)

        self.assertTrue(self.client.login(
            username=self.username, password=self.password),
            'Failed to login user %s' % self.email)

        factory = RequestFactory()
        request = factory.get('/admin')
        request.user = self.user
        request.session = {}

        self.request = request
        self.settings_admin = SettingsAdmin(get_usersettings_model(), AdminSite())

        # Hack to test this function as it calls 'messages.add'
        # See https://code.djangoproject.com/ticket/17971
        setattr(self.request, 'session', 'session')
        messages = FallbackStorage(self.request)
        setattr(self.request, '_messages', messages) 
Example 2
Project: django-users2   Author: mishbahr   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def setUp(self):
        get_user_model().objects.create_superuser(self.user_email, self.user_password)

        self.assertTrue(self.client.login(
            username=self.user_email, password=self.user_password),
            'Failed to login user %s' % self.user_email)

        get_user_model().objects.create_user('user1@example.com', 'pa$sw0Rd1', is_active=False)

        factory = RequestFactory()
        self.request = factory.get('/admin')

        # Hack to test this function as it calls 'messages.add'
        # See https://code.djangoproject.com/ticket/17971
        setattr(self.request, 'session', 'session')
        messages = FallbackStorage(self.request)
        setattr(self.request, '_messages', messages) 
Example 3
Project: arches   Author: archesproject   File: api_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_api_base_view(self):
        """
        Test that our custom header parameters get pushed on to the GET QueryDict

        """

        factory = RequestFactory(HTTP_X_ARCHES_VER="2.1")
        view = APIBase.as_view()

        request = factory.get(reverse("mobileprojects", kwargs={}), {"ver": "2.0"})
        request.user = None
        response = view(request)
        self.assertEqual(request.GET.get("ver"), "2.0")

        request = factory.get(reverse("mobileprojects"), kwargs={})
        request.user = None
        response = view(request)
        self.assertEqual(request.GET.get("ver"), "2.1") 
Example 4
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 6 votes vote down vote up
def setUp(self):

        self.addresses = {
            'shipping_name': '',
            'shipping_address_line1': '',
            'shipping_address_city': '',
            'shipping_address_zip': '',
            'shipping_address_country': '',
            'billing_name': '',
            'billing_address_line1': '',
            'billing_address_city': '',
            'billing_address_zip': '',
            'billing_address_country': ''
        }
        self.email = "test@test.com"
        self.request = RequestFactory().get('/')
        self.request.session = {}
        self.basket_id = basket_id(self.request) 
Example 5
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 6 votes vote down vote up
def test_post_checkout(self):
        """
        Test correctly posting to the checkout view
        """
        country = CountryFactory()
        request = RequestFactory().post(
            reverse_lazy('longclaw_checkout_view'),
            {
                'shipping-name': 'bob',
                'shipping-line_1': 'blah blah',
                'shipping-postcode': 'ytxx 23x',
                'shipping-city': 'London',
                'shipping-country': country.pk,
                'email': 'test@test.com'
            }
        )
        request.session = {}
        bid = basket_id(request)
        BasketItemFactory(basket_id=bid)
        response = CheckoutView.as_view()(request)
        self.assertEqual(response.status_code, 302) 
Example 6
Project: django-defender   Author: jazzband   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_get_ip_reverse_proxy(self):
        """ Tests if can handle a long user agent
        """
        request_factory = RequestFactory()
        request = request_factory.get(ADMIN_LOGIN_URL)
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["HTTP_X_FORWARDED_FOR"] = "192.168.24.24"
        self.assertEqual(utils.get_ip(request), "192.168.24.24")

        request_factory = RequestFactory()
        request = request_factory.get(ADMIN_LOGIN_URL)
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["REMOTE_ADDR"] = "24.24.24.24"
        self.assertEqual(utils.get_ip(request), "24.24.24.24") 
Example 7
Project: django-defender   Author: jazzband   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_login_non_blocked_for_non_standard_login_views_different_msg(self):
        """
        Check that a view wich returns the expected status code but not the
        expected message is not causing the IP to be locked out.
        """

        @watch_login(status_code=401, msg="Invalid credentials")
        def fake_api_401_login_view_without_msg(request):
            """ Fake the api login with 401 """
            return HttpResponse("Ups, wrong credentials", status=401)

        request_factory = RequestFactory()
        request = request_factory.post("api/login")
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["HTTP_X_FORWARDED_FOR"] = "192.168.24.24"

        for _ in range(4):
            fake_api_401_login_view_without_msg(request)

            data_out = utils.get_blocked_ips()
            self.assertEqual(data_out, []) 
Example 8
Project: kobo-predict   Author: awemulya   File: test_audit_log.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_audit_log_call(self):
        account_user = User(username="alice")
        request_user = User(username="bob")
        request = RequestFactory().get("/")
        # create a log
        audit = {}
        audit_log(Actions.FORM_PUBLISHED, request_user, account_user,
                  "Form published", audit, request)
        # function should just run without exception so we are good at this
        # point query for this log entry
        sort = {"created_on": -1}
        cursor = AuditLog.query_mongo(
            account_user.username, None, None, sort, 0, 1)
        self.assertTrue(cursor.count() > 0)
        record = cursor.next()
        self.assertEqual(record['account'], "alice")
        self.assertEqual(record['user'], "bob")
        self.assertEqual(record['action'], Actions.FORM_PUBLISHED) 
Example 9
Project: django-useraudit   Author: muccg   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def simulate_login(username, password, headers=None):
    rf = RequestFactory()
    request = rf.request(**headers)
    engine = import_module(settings.SESSION_ENGINE)
    request.session = engine.SessionStore()

    # TODO remove when we don't support Django 1.10 anymore
    # request passed in to authenticate only after Django 1.10
    # Also the middleware saving the request to thread local can be dropped
    try:
        user = authenticate(request, username=username, password=password)
    except TypeError:
        middleware.thread_data.request = request
        user = authenticate(username=username, password=password)
    if user:
        login(request, user) 
Example 10
Project: django-auth-ldap   Author: django-auth-ldap   File: tests.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_callable_server_uri(self):
        request = RequestFactory().get("/")
        cb_mock = mock.Mock(return_value=self.server.ldap_uri)

        self._init_settings(
            SERVER_URI=lambda request: cb_mock(request),
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
        )
        user_count = User.objects.count()

        user = authenticate(request=request, username="alice", password="password")

        self.assertIs(user.has_usable_password(), False)
        self.assertEqual(user.username, "alice")
        self.assertEqual(User.objects.count(), user_count + 1)
        cb_mock.assert_called_with(request) 
Example 11
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_changelist_view(self):
        request = RequestFactory().get('/')
        request.user = User.objects.create(username='name', password='pass', is_superuser=True)
        admin_obj = PreferencesAdmin(MyPreferences, admin.site)

        # With only one preferences object redirect to its change view.
        response = admin_obj.changelist_view(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/admin/tests/mypreferences/1/change/')

        # With multiple preferences display listing view.
        MyPreferences.objects.create()
        response = admin_obj.changelist_view(request)
        response.render()
        self.failUnless('changelist-form' in response.content, 'Should \
display listing if multiple preferences objects are available.') 
Example 12
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_preferences_cp(self):
        request = RequestFactory().get('/')
        context = context_processors.preferences_cp(request)

        # context should have preferences.
        my_preferences = context['preferences']

        # preferences should have test MyPreferences object member.
        my_preferences = my_preferences.MyPreferences
        self.failUnless(isinstance(my_preferences, MyPreferences),
                        "%s should be instance of MyPreferences." % my_preferences)

        # With preferences_cp is loaded as a TEMPLATE_CONTEXT_PROCESSORS
        # templates should have access to preferences object.
        context_instance = RequestContext(request)
        t = Template("{% if preferences %}{{ preferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "preferences should be \
available in template context.")

        t = Template("{% if preferences.MyPreferences %}{{ \
preferences.MyPreferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "MyPreferences should be \
available as part of preferences var in template context.") 
Example 13
Project: django-warrant   Author: MetaMetricsInc   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_add_user_tokens_signal(self):
        User = get_user_model()
        user = User.objects.create(username=settings.COGNITO_TEST_USERNAME)
        user.access_token = 'access_token_value'
        user.id_token = 'id_token_value'
        user.refresh_token = 'refresh_token_value'
        user.backend = 'warrant.django.backend.CognitoBackend'
        user.api_key = 'abcdefg'
        user.api_key_id = 'ab-1234'

        request = RequestFactory().get('/login')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        signals.user_logged_in.send(sender=user.__class__, request=request, user=user)

        self.assertEqual(request.session['ACCESS_TOKEN'], 'access_token_value')
        self.assertEqual(request.session['ID_TOKEN'], 'id_token_value')
        self.assertEqual(request.session['REFRESH_TOKEN'], 'refresh_token_value')
        self.assertEqual(request.session['API_KEY'], 'abcdefg')
        self.assertEqual(request.session['API_KEY_ID'], 'ab-1234') 
Example 14
Project: wagtail-personalisation   Author: wagtail   File: rules.py    License: MIT License 6 votes vote down vote up
def get_user_info_string(self, user):
        # Local import for cyclic import
        from wagtail_personalisation.adapters import (
            get_segment_adapter, SessionSegmentsAdapter, SEGMENT_ADAPTER_CLASS)

        # Create a fake request so we can use the adapter
        request = RequestFactory().get('/')
        request.user = user

        # If we're using the session adapter check for an active session
        if SEGMENT_ADAPTER_CLASS == SessionSegmentsAdapter:
            request.session = self._get_user_session(user)
        else:
            request.session = SessionStore()

        adapter = get_segment_adapter(request)
        visit_count = adapter.get_visit_count(self.counted_page)
        return str(visit_count) 
Example 15
Project: django-rest-framework-json-api   Author: django-json-api   File: test_relations.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        super(TestHyperlinkedFieldBase, self).setUp()
        self.blog = Blog.objects.create(name='Some Blog', tagline="It's a blog")
        self.entry = Entry.objects.create(
            blog=self.blog,
            headline='headline',
            body_text='body_text',
            pub_date=timezone.now(),
            mod_date=timezone.now(),
            n_comments=0,
            n_pingbacks=0,
            rating=3
        )
        self.comment = Comment.objects.create(
            entry=self.entry,
            body='testing one two three',
        )

        self.request = RequestFactory().get(reverse('entry-detail', kwargs={'pk': self.entry.pk}))
        self.view = EntryViewSet(request=self.request, kwargs={'entry_pk': self.entry.id}) 
Example 16
Project: volontulo   Author: CodeForPoznan   File: test_current_user.py    License: MIT License 6 votes vote down vote up
def test_post_read_only(self):
        self.client.force_login(self.user)
        user_before = UserSerializer(
            self.user,
            context={'request': RequestFactory().get('/')},
        ).data

        res = self.client.post(
            ENDPOINT_URL,
            {
                'email': 'X',
                'is_administrator': True,
                'organizations': [1],
                'username': 'Mikey X',
            },
            format='json',
        )

        self.assertEqual(res.status_code, 200)
        self.assertDictEqual(res.data, user_before) 
Example 17
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        factory = RequestFactory()
        self.request = factory.get('/', {'page': 3, 'sort': 'asc'})
        self.request.user = AnonymousUser()
        # Simulate that we get throught the middleware
        self.request.franchise = None 
Example 18
Project: django-accounting   Author: dulacp   File: context_processors_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        factory = RequestFactory()
        self.request = factory.get('/')
        self.metadata = metadata(self.request) 
Example 19
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 5 votes vote down vote up
def get_factory(self):
        return RequestFactory() 
Example 20
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_country_and_code(self):
        request = RequestFactory().get('/', { 'country_code': 'US' })
        api_request = upgrade_to_api_request(request)
        with self.assertRaises(InvalidShippingCountry):
            get_shipping_cost_kwargs(api_request, country=self.country.pk) 
Example 21
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_destination_does_not_exist(self):
        non_existant_pk = 2147483647
        self.assertFalse(Address.objects.filter(pk=non_existant_pk).exists())
        request = RequestFactory().get('/', { 'country_code': 'US', 'destination': str(non_existant_pk) })
        api_request = upgrade_to_api_request(request)
        with self.assertRaises(InvalidShippingCountry):
            get_shipping_cost_kwargs(api_request, country=self.country.pk) 
Example 22
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_no_country_or_code(self):
        request = RequestFactory().get('/')
        api_request = upgrade_to_api_request(request)
        with self.assertRaises(InvalidShippingCountry):
            get_shipping_cost_kwargs(api_request) 
Example 23
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_only_country_code(self):
        request = RequestFactory().get('/', { 'country_code': 'US' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.assertEqual(result['country_code'], 'US')
        self.assertEqual(result['destination'], None)
        self.assertEqual(result['basket_id'], basket_id(api_request))
        self.assertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.assertEqual(result['name'], 'standard') 
Example 24
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_country_code_and_shipping_rate_name(self):
        request = RequestFactory().get('/', { 'country_code': 'US', 'shipping_rate_name': 'foo' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.assertEqual(result['country_code'], 'US')
        self.assertEqual(result['destination'], None)
        self.assertEqual(result['basket_id'], basket_id(api_request))
        self.assertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.assertEqual(result['name'], 'foo') 
Example 25
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_only_country_known_iso(self):
        request = RequestFactory().get('/')
        api_request = upgrade_to_api_request(request)
        country = Country.objects.create(iso='ZZ', name_official='foo', name='foo')
        result = get_shipping_cost_kwargs(api_request, country=country.pk)
        self.assertEqual(result['country_code'], 'ZZ')
        self.assertEqual(result['destination'], None)
        self.assertEqual(result['basket_id'], basket_id(api_request))
        self.assertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.assertEqual(result['name'], 'standard') 
Example 26
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_with_destination(self):
        destination = AddressFactory()
        request = RequestFactory().get('/', { 'destination': destination.pk })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.assertEqual(result['country_code'], destination.country.pk)
        self.assertEqual(result['destination'], destination)
        self.assertEqual(result['basket_id'], basket_id(api_request))
        self.assertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.assertEqual(result['name'], 'standard') 
Example 27
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_shipping_cost_kwargs_with_destination_and_country_code(self):
        destination = AddressFactory()
        request = RequestFactory().get('/', { 'destination': destination.pk, 'country_code': '11' })
        api_request = upgrade_to_api_request(request)
        result = get_shipping_cost_kwargs(api_request)
        self.assertNotEqual(str(destination.country.pk), '11')
        self.assertEqual(result['country_code'], '11')
        self.assertEqual(result['destination'], destination)
        self.assertEqual(result['basket_id'], basket_id(api_request))
        self.assertEqual(result['settings'], Configuration.for_site(api_request.site))
        self.assertEqual(result['name'], 'standard') 
Example 28
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        """Create a basket with things in it
        """
        request = RequestFactory().get('/')
        request.session = {}
        self.bid = bid = basket_id(request)
        self.item = BasketItemFactory(basket_id=bid)
        BasketItemFactory(basket_id=bid)
        
        self.address = address = AddressFactory()
        
        self.rate1 = ShippingRate.objects.create(
            name='98d17c43-7e20-42bd-b603-a4c83c829c5a',
            rate=99,
            carrier='8717ca67-4691-4dff-96ec-c43cccd15241',
            description='313037e1-644a-4570-808a-f9ba82ecfb34',
            basket_id=bid,
        )
        
        self.rate2 = ShippingRate.objects.create(
            name='8e721550-594c-482b-b512-54dc1744dff8',
            rate=97,
            carrier='4f4cca35-1a7a-47ec-ab38-a9918e0c04af',
            description='eacb446d-eb17-4ea7-82c1-ac2f62a53a7d',
            basket_id=bid,
            destination=address,
        )
        
        self.rate3 = ShippingRate.objects.create(
            name='72991859-dc0b-463e-821a-bf8b04aaed2c',
            rate=95,
            carrier='0aa3c318-b045-4a96-a456-69b4cc71d46a',
            description='78b03c47-b20f-4f91-8161-47340367fb34',
            destination=address,
        ) 
Example 29
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.shipping_address = AddressFactory()
        self.billing_address = AddressFactory()
        self.email = "test@test.com"
        self.request = RequestFactory().get('/')
        self.request.session = {}
        self.request.site = Site.find_for_request(self.request)
        self.basket_id = basket_id(self.request)
        BasketItemFactory(basket_id=self.basket_id) 
Example 30
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_get_checkout(self):
        """
        Test the checkout GET view
        """
        request = RequestFactory().get(reverse_lazy('longclaw_checkout_view'))
        response = CheckoutView.as_view()(request)
        self.assertEqual(response.status_code, 200)