本文整理汇总了Python中test_utils.RequestFactory类的典型用法代码示例。如果您正苦于以下问题:Python RequestFactory类的具体用法?Python RequestFactory怎么用?Python RequestFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestFactory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_multiple_shared_works
def test_multiple_shared_works(self):
request = RequestFactory().post(
"/api",
HTTP_AUTHORIZATION="mkt-shared-secret "
"[email protected],56b6f1a3dd735d962c56"
"ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb"
"9c68c31b3371aa8130317815c89e5072e31bb94b4"
"121c5c165f3515838d4d6c60c4,165d631d3c3045"
"458b4516242dad7ae",
)
drf_request = Request(request)
# Start with an AnonymousUser on the request, because that's a classic
# situation: we already went through a middleware, it didn't find a
# session cookie, if set request.user = AnonymousUser(), and now we
# are going through the authentication code in the API.
request.user = AnonymousUser()
# Call middleware as they would normally be called.
RedirectPrefixedURIMiddleware().process_request(request)
RestSharedSecretMiddleware().process_request(request)
RestOAuthMiddleware().process_request(request)
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication(),
)
eq_(drf_request.user, self.profile.user)
eq_(drf_request._request.user, self.profile.user)
eq_(drf_request.user.is_authenticated(), True)
eq_(drf_request._request.user.is_authenticated(), True)
eq_(drf_request.amo_user.pk, self.profile.pk)
eq_(drf_request._request.amo_user.pk, self.profile.pk)
开发者ID:robhudson,项目名称:zamboni,代码行数:34,代码来源:test_authentication.py
示例2: render
def render(self, name, value, attrs=None):
topics_and_subtopics = Topic.objects.all()
topics = [t for t in topics_and_subtopics if t.parent_id is None]
for topic in topics:
self.process_topic(value, topic)
topic.my_subtopics = [t for t in topics_and_subtopics
if t.parent_id == topic.id]
for subtopic in topic.my_subtopics:
self.process_topic(value, subtopic)
# Create a fake request to make jingo happy.
req = RequestFactory()
req.META = {}
req.locale = settings.WIKI_DEFAULT_LANGUAGE
return jingo.render_to_string(
req,
'wiki/includes/topics_widget.html',
{
'topics': topics,
'name': name,
})
开发者ID:DWDRAEGER,项目名称:kitsune,代码行数:25,代码来源:widgets.py
示例3: render_email
def render_email(template, context):
"""Renders a template in the currently set locale."""
req = RequestFactory()
req.META = {}
req.locale = translation.get_language()
return jingo.render_to_string(req, template, context)
开发者ID:jasdeepdhillon13,项目名称:kitsune,代码行数:7,代码来源:email_utils.py
示例4: dump_app
def dump_app(id, **kw):
# Because @robhudson told me to.
from mkt.api.resources import AppResource
# Note: not using storage because all these operations should be local.
target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
str(id / 1000))
target_file = os.path.join(target_dir, str(id) + '.json')
try:
obj = Webapp.objects.get(pk=id)
except Webapp.DoesNotExist:
task_log.info(u'Webapp does not exist: {0}'.format(id))
return
req = RequestFactory().get('/')
req.user = AnonymousUser()
req.REGION = WORLDWIDE
if not os.path.exists(target_dir):
os.makedirs(target_dir)
task_log.info('Dumping app {0} to {1}'.format(id, target_file))
res = AppResource().dehydrate_objects([obj], request=req)
json.dump(res[0], open(target_file, 'w'), cls=JSONEncoder)
return target_file
开发者ID:chrisdavidmills,项目名称:zamboni,代码行数:25,代码来源:tasks.py
示例5: req_factory_factory
def req_factory_factory(url, user=None):
"""Creates a request factory, logged in with the user."""
req = RequestFactory().get(url)
if user:
req.user = user.user
req.groups = req.user.get_profile().groups.all()
return req
开发者ID:chilyashev,项目名称:zamboni,代码行数:7,代码来源:__init__.py
示例6: _make_resp
def _make_resp(mw_cls, secure=False):
mw = mw_cls()
req = RequestFactory().get('/')
if secure:
req.is_secure = lambda: True
resp = mw.process_response(req, HttpResponse())
return resp
开发者ID:Mondego,项目名称:pyreco,代码行数:7,代码来源:allPythonContent.py
示例7: test_session_auth
def test_session_auth(self):
req = RequestFactory().get('/')
req.COOKIES['user'] = ('[email protected],56b6f1a3dd735d962c56ce7d8f46e02ec'
'1d4748d2c00c407d75f0969d08bb9c68c31b3371aa8130'
'317815c89e5072e31bb94b4121c5c165f3515838d4d6c6'
'0c4,165d631d3c3045458b4516242dad7ae')
ok_(self.auth.is_authenticated(req))
开发者ID:sandy-slin,项目名称:zamboni,代码行数:7,代码来源:test_authentication.py
示例8: test_session_auth_no_post
def test_session_auth_no_post(self):
req = RequestFactory().post('/api/')
req.user = AnonymousUser()
for m in self.middlewares:
m().process_request(req)
ok_(not self.auth.authenticate(Request(req)))
ok_(not req.user.is_authenticated())
开发者ID:JaredKerim-Mozilla,项目名称:zamboni,代码行数:7,代码来源:test_authentication.py
示例9: check_appver_filters
def check_appver_filters(self, appver, expected):
request = RequestFactory()
request.APP = amo.FIREFOX
facets = {
u'platforms': [{
u'count': 58,
u'term': 1
}],
u'appversions': [{
u'count': 58,
u'term': 5000000200100
}],
u'categories': [{
u'count': 55,
u'term': 1
}],
u'tags': []
}
versions = version_sidebar(request, {'appver': floor_version(appver)},
facets)
all_ = versions.pop(0)
eq_(all_.text, 'Any %s' % unicode(request.APP.pretty))
eq_(all_.selected, not expected)
return [v.__dict__ for v in versions]
开发者ID:atsay,项目名称:zamboni,代码行数:28,代码来源:test_views.py
示例10: dump_app
def dump_app(id, **kw):
from mkt.webapps.api import AppSerializer
# Because @robhudson told me to.
# Note: not using storage because all these operations should be local.
target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
str(id / 1000))
target_file = os.path.join(target_dir, str(id) + '.json')
try:
obj = Webapp.objects.get(pk=id)
except Webapp.DoesNotExist:
task_log.info(u'Webapp does not exist: {0}'.format(id))
return
req = RequestFactory().get('/')
req.user = AnonymousUser()
req.REGION = RESTOFWORLD
if not os.path.exists(target_dir):
os.makedirs(target_dir)
task_log.info('Dumping app {0} to {1}'.format(id, target_file))
res = AppSerializer(obj, context={'request': req}).data
json.dump(res, open(target_file, 'w'), cls=JSONEncoder)
return target_file
开发者ID:prodigeni,项目名称:zamboni,代码行数:25,代码来源:tasks.py
示例11: test_multiple_shared_works
def test_multiple_shared_works(self):
request = RequestFactory().post(
'/',
HTTP_AUTHORIZATION='mkt-shared-secret '
'[email protected],56b6f1a3dd735d962c56'
'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
'9c68c31b3371aa8130317815c89e5072e31bb94b4'
'121c5c165f3515838d4d6c60c4,165d631d3c3045'
'458b4516242dad7ae')
drf_request = Request(request)
# Start with an AnonymousUser on the request, because that's a classic
# situation: we already went through a middleware, it didn't find a
# session cookie, if set request.user = AnonymousUser(), and now we
# are going through the authentication code in the API.
request.user = AnonymousUser()
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication())
eq_(drf_request.user, self.profile.user)
eq_(drf_request._request.user, self.profile.user)
eq_(drf_request.user.is_authenticated(), True)
eq_(drf_request._request.user.is_authenticated(), True)
eq_(drf_request.amo_user.pk, self.profile.pk)
eq_(drf_request._request.amo_user.pk, self.profile.pk)
开发者ID:aricha,项目名称:zamboni,代码行数:26,代码来源:test_authentication.py
示例12: TestAddSubmissionView
class TestAddSubmissionView(TestCase):
def __init__(self, *args, **kwargs):
super(TestAddSubmissionView, self).__init__(*args, **kwargs)
# Add context and template to the response
on_template_render = curry(store_rendered_templates, {})
signals.template_rendered.connect(on_template_render,
dispatch_uid="template-render")
def setUp(self):
self.factory = RequestFactory()
self.ideation = MagicMock()
def test_add_submission_get(self):
request = self.factory.get('/')
request.user = AnonymousUser()
request.development = development_mock
response = views.add_submission(request, self.ideation)
eq_(response.status_code, 200)
def test_invalid_form(self):
request = self.factory.post('/', BLANK_EXTERNALS)
request.user = AnonymousUser()
request.development = development_mock
response = views.add_submission(request, self.ideation)
eq_(response.status_code, 200)
开发者ID:hfeeki,项目名称:mozilla-ignite,代码行数:26,代码来源:test_views.py
示例13: TestDRFSwitch
class TestDRFSwitch(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_responses(self):
view = SwitchToDRF('LanguageView')
request = self.factory.get(reverse('api.language', args=['1.5']))
request.APP = Mock(id=1)
request.user = AnonymousUser()
eq_(view(request, api_version=1.5).__module__, 'django.http')
piston_response = view(request, api_version=1.5).content
self.create_switch('drf', db=True)
eq_(view(request, api_version=1.5).__module__,
'rest_framework.response')
drf_response = view(request, api_version=1.5).render().content
eq_(piston_response, drf_response)
def test_wrong_format_exceptions(self):
view = SwitchToDRF('LanguageView')
request = self.factory.get(reverse('api.language', args=['1.5']))
request.APP = Mock(id=1)
request.GET = {'format': 'foo'}
request.user = AnonymousUser()
response = view(request, api_version=1.5)
eq_(response.content, '{"msg": "Not implemented yet."}')
eq_(response.status_code, 200)
self.create_switch('drf', db=True)
response = view(request, api_version=1.5)
self.assertTrue('<error>Not found</error>'
in response.render().content)
eq_(response.status_code, 404)
开发者ID:Kolonahe,项目名称:olympia,代码行数:32,代码来源:test_urls.py
示例14: TestProfileMiddleware
class TestProfileMiddleware(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_safe_view_request(self):
request = self.factory.get(reverse("users_edit"))
middleware = ProfileMiddleware()
response = middleware.process_request(request)
self.assertFalse(response)
def test_safe_path_request(self):
request = self.factory.get("/admin/something/")
middleware = ProfileMiddleware()
response = middleware.process_request(request)
self.assertFalse(response)
def test_authed_user_request(self):
request = self.factory.get(reverse("users_dashboard"))
request.user = complete_user
middleware = ProfileMiddleware()
response = middleware.process_request(request)
self.assertFalse(response)
def test_anon_user_request(self):
request = self.factory.get(reverse("users_dashboard"))
request.user = incomplete_user
middleware = ProfileMiddleware()
response = middleware.process_request(request)
self.assertEqual(response.status_code, 302)
self.assertEqual(response["Location"], reverse("users_edit"))
开发者ID:JingzheTian,项目名称:popcorn_maker,代码行数:30,代码来源:midddleware_tests.py
示例15: get_request
def get_request(self, data=None):
if data is None:
data = {}
request = RequestFactory().get("/", data)
request.REGION = mkt.regions.RESTOFWORLD
request.API = True
return request
开发者ID:BIGGANI,项目名称:zamboni,代码行数:7,代码来源:test_serializers.py
示例16: _create_mocked_tweet_request
def _create_mocked_tweet_request(self):
request = RequestFactory().post(
reverse('customercare.twitter_post'),
{'reply_to': 1,
'content': '@foobar try Aurora! #fxhelp'})
request.session = {}
request.twitter = Mock()
request.twitter.authed = True
request.twitter.api = Mock()
return_value = {
'id': 123456790,
'text': '@foobar try Aurora! #fxhelp',
'created_at': datetime.strftime(datetime.utcnow(),
'%a %b %d %H:%M:%S +0000 %Y'),
'user': {
'lang': 'en',
'id': 42,
'screen_name': 'r1cky',
'profile_image_url': 'http://example.com/profile.jpg',
'profile_image_url_https': 'https://example.com/profile.jpg',
}
}
request.twitter.api.update_status.return_value = return_value
credentials = {'screen_name': 'r1cky'}
request.twitter.api.verify_credentials.return_value = credentials
request.user = Mock()
request.user.is_authenticated.return_value = False
return request
开发者ID:Archaeopteryx,项目名称:kitsune,代码行数:28,代码来源:test_views.py
示例17: test_only_code
def test_only_code(self):
"""GeoIP code is included when the country name is missing."""
req = RequestFactory()
req.COOKIES = {
'geoip_country_code': 'US',
}
val = geoip_cache_detector(req)
eq_(val['include_geoip'], True)
开发者ID:Archaeopteryx,项目名称:kitsune,代码行数:8,代码来源:test_context_processors.py
示例18: test_authenticated
def test_authenticated(self, unread_count_for):
"""Test authenticated user with flag active."""
unread_count_for.return_value = 3
rf = RequestFactory()
request = rf.get("/")
request.user = user(save=True)
eq_(3, unread_message_count(request)["unread_message_count"])
assert unread_count_for.called
开发者ID:klrmn,项目名称:kitsune,代码行数:8,代码来源:test_context_processors.py
示例19: test_authenticated
def test_authenticated(self, unread_count_for):
"""Test authenticated user with flag active."""
unread_count_for.return_value = 3
rf = RequestFactory()
request = rf.get('/')
request.user = get_user('rrosario')
eq_(3, unread_message_count(request)['unread_message_count'])
assert unread_count_for.called
开发者ID:erikrose,项目名称:kitsune,代码行数:8,代码来源:test_context_processors.py
示例20: test_anonymous
def test_anonymous(self, unread_count_for):
"""Test anonymous user with flag active."""
unread_count_for.return_value = 3
rf = RequestFactory()
request = rf.get('/')
request.user = AnonymousUser()
eq_(0, unread_message_count(request)['unread_message_count'])
assert not unread_count_for.called
开发者ID:erikrose,项目名称:kitsune,代码行数:8,代码来源:test_context_processors.py
注:本文中的test_utils.RequestFactory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论