Python django.test.client.RequestFactory() Examples
The following are 30
code examples of django.test.client.RequestFactory().
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 also want to check out all available functions/classes of the module
django.test.client
, or try the search function
.
Example #1
Source File: test_admin.py From django-usersettings2 with BSD 3-Clause "New" or "Revised" License | 8 votes |
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
Source File: test_admin.py From django-users2 with BSD 3-Clause "New" or "Revised" License | 7 votes |
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
Source File: test_audit_log.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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 #4
Source File: rules.py From wagtail-personalisation with MIT License | 6 votes |
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 #5
Source File: test_relations.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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 #6
Source File: tests.py From longclaw with MIT License | 6 votes |
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 #7
Source File: tests.py From django-defender with Apache License 2.0 | 6 votes |
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
Source File: tests.py From django-defender with Apache License 2.0 | 6 votes |
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 #9
Source File: tests.py From longclaw with MIT License | 6 votes |
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 #10
Source File: tests.py From django-warrant with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #11
Source File: utils.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #12
Source File: test_current_user.py From volontulo with MIT License | 6 votes |
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 #13
Source File: tests.py From django-auth-ldap with BSD 2-Clause "Simplified" License | 6 votes |
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 #14
Source File: test_all.py From DCRM with GNU Affero General Public License v3.0 | 6 votes |
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 #15
Source File: test_all.py From DCRM with GNU Affero General Public License v3.0 | 6 votes |
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 #16
Source File: api_tests.py From arches with GNU Affero General Public License v3.0 | 6 votes |
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 #17
Source File: tests.py From Collaboration-System with GNU General Public License v2.0 | 5 votes |
def setup(self): self.factory = RequestFactory() self.user1 = User.objects.create(username="user1", password="pwd", email="example@example.com") self.user2 = User.objects.create(username="user2", password="pwd", email="example@example.com") self.comm = Community.objects.create(name='fake_community', desc='fake',image='/home/karthik/Downloads/index.jpg',category='fake', created_by=self.user1, tag_line='always fake',forum_link='jvajds') self.grp = Group.objects.create(name='fake_grp', desc='I am fake', image='/home/karthik/Downloads/index.jpg',visibility=True, created_by=self.user1) self.commgrp = CommunityGroups.objects.create(group=self.grp, user=self.user3, community=self.comm) self.draft=States.objects.create(name='draft') self.private = States.objects.create(name='private') self.visible=States.objects.create(name='visible') self.publishable=States.objects.create(name='publishable') self.publish=States.objects.create(name='publish') self.article1 = Articles.objects.create(title='fake_article1', body='abc', created_by=self.user1, state=self.visible) self.article2 = Articles.objects.create(title='fake_article2', body='abc', created_by=self.user1, state=self.visible) self.article3 = Articles.objects.create(title='fake_article3', body='abc', created_by=self.user1, state=self.visible) self.article4 = Articles.objects.create(title='fake_article4', body='abc', created_by=self.user1, state=self.visible) self.article5 = Articles.objects.create(title='fake_article5', body='abc', created_by=self.user1, state=self.visible) self.article6 = Articles.objects.create(title='fake_article6', body='abc', created_by=self.user1, state=self.visible) self.comm_article = CommunityArticles.objects.create(article=self.article1, community=self.comm, user=self.user1) self.comm_article = CommunityArticles.objects.create(article=self.article2, community=self.comm, user=self.user1) self.comm_article = CommunityArticles.objects.create(article=self.article3, community=self.comm, user=self.user1) self.comm_article = CommunityArticles.objects.create(article=self.article4, community=self.comm, user=self.user1) self.comm_article = CommunityArticles.objects.create(article=self.article5, community=self.comm, user=self.user1) self.comm_article = CommunityArticles.objects.create(article=self.article6, community=self.comm, user=self.user1) #def test_recommendationtest(self): # request = initiate_get(self) # response = view_article(request, pk)
Example #18
Source File: adapters_test.py From codesy with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): self.csaa = CodesySocialAccountAdapter() self.request = RequestFactory() self.sociallogin = fudge.Fake()
Example #19
Source File: test_viewsets.py From dynamic-rest with MIT License | 5 votes |
def setUp(self): self.view = UserViewSet() self.rf = RequestFactory()
Example #20
Source File: test_permissions.py From lego with MIT License | 5 votes |
def setUp(self): self.factory = RequestFactory() self.permission_class = HealthChecksPermission()
Example #21
Source File: test_viewsets.py From dynamic-rest with MIT License | 5 votes |
def setUp(self): self.fixture = create_fixture() self.view = GroupNoMergeDictViewSet.as_view({'post': 'create'}) self.rf = RequestFactory()
Example #22
Source File: test_utils.py From mozilla-django-oidc with Mozilla Public License 2.0 | 5 votes |
def test_absolutify_https(self): req = RequestFactory( HTTP_X_FORWARDED_PROTO='https' ).get('/', SERVER_PORT=443) url = absolutify(req, '/foo/bar') self.assertEqual(url, 'https://testserver/foo/bar')
Example #23
Source File: tests.py From django-warrant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setUp(self): self.factory = RequestFactory()
Example #24
Source File: tests.py From django-warrant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_model_backend(self): """ Check that the logged in signal plays nice with other backends """ User = get_user_model() user = User.objects.create(username=settings.COGNITO_TEST_USERNAME) user.backend = 'django.contrib.auth.backends.ModelBackend' 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)
Example #25
Source File: test_menu_items.py From wagtailmenus with MIT License | 5 votes |
def setUp(self): self.rf = RequestFactory()
Example #26
Source File: utils.py From wagtailmenus with MIT License | 5 votes |
def make_contextualvals_instance( url='/', request=None, parent_context=None, current_site=None, current_level=1, original_menu_tag='', original_menu_instance=None, current_page=None, current_section_root_page=None, current_page_ancestor_ids=(), ): if request is None: rf = RequestFactory() request = rf.get(url) if parent_context is None: parent_context = RequestContext(request, {}) return ContextualVals( parent_context, request, current_site, current_level, original_menu_tag, original_menu_instance, current_page, current_section_root_page, current_page_ancestor_ids, )
Example #27
Source File: test_feed.py From django-ical with MIT License | 5 votes |
def test_file_header(self): request = RequestFactory().get("/test/ical") view = TestFilenameFeed() response = view(request) header = b"BEGIN:VCALENDAR\r\nVERSION:2.0" self.assertTrue(response.content.startswith(header))
Example #28
Source File: test_feed.py From django-ical with MIT License | 5 votes |
def test_file_type(self): request = RequestFactory().get("/test/ical") view = TestFilenameFeed() response = view(request) self.assertIn("Content-Type", response) self.assertEqual( response["content-type"], "text/calendar, text/x-vcalendar, application/hbs-vcs", )
Example #29
Source File: test_feed.py From django-ical with MIT License | 5 votes |
def test_file_name(self): request = RequestFactory().get("/test/ical") view = TestFilenameFeed() response = view(request) self.assertIn("Content-Disposition", response) self.assertEqual( response["content-disposition"], 'attachment; filename="123.ics"' )
Example #30
Source File: test_feed.py From django-ical with MIT License | 5 votes |
def test_wr_timezone(self): """ Test for the x-wr-timezone property. """ class TestTimezoneFeed(TestICalFeed): timezone = "Asia/Tokyo" request = RequestFactory().get("/test/ical") view = TestTimezoneFeed() response = view(request) calendar = icalendar.Calendar.from_ical(response.content) self.assertEquals(calendar["X-WR-TIMEZONE"], "Asia/Tokyo")