本文整理匯總了Python中django.test.client.RequestFactory方法的典型用法代碼示例。如果您正苦於以下問題:Python client.RequestFactory方法的具體用法?Python client.RequestFactory怎麽用?Python client.RequestFactory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.test.client
的用法示例。
在下文中一共展示了client.RequestFactory方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setUp
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例2: test_api_base_view
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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")
示例3: setUp
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例4: test_post_checkout
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例5: test_get_ip_reverse_proxy
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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")
示例6: test_login_non_blocked_for_non_standard_login_views_different_msg
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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, [])
示例7: test_audit_log_call
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例8: simulate_login
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例9: test_callable_server_uri
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例10: test_changelist_view
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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.')
示例11: test_preferences_cp
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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.")
示例12: test_add_user_tokens_signal
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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')
示例13: get_user_info_string
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)
示例14: setUp
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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})
示例15: setUp
# 需要導入模塊: from django.test import client [as 別名]
# 或者: from django.test.client import RequestFactory [as 別名]
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)