我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用django.test.client.RequestFactory()。
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.')
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.")
def test_debug(self): """ If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL """ request = RequestFactory().get('/') context = {"request": request} # convert to generator common_bundle = (chunk for chunk in FAKE_COMMON_BUNDLE) get_bundle = Mock(return_value=common_bundle) loader = Mock(get_bundle=get_bundle) bundle_name = 'bundle_name' with patch('ui.templatetags.render_bundle.get_loader', return_value=loader) as get_loader: assert render_bundle(context, bundle_name) == ( '<script type="text/javascript" src="{base}/{filename}" >' '</script>'.format( base=webpack_dev_server_url(request), filename=FAKE_COMMON_BUNDLE[0]['name'], ) ) assert public_path(request) == webpack_dev_server_url(request) + "/" get_bundle.assert_called_with(bundle_name) get_loader.assert_called_with('DEFAULT')
def test_production(self): """ If USE_WEBPACK_DEV_SERVER=False, return a static URL for production """ request = RequestFactory().get('/') context = {"request": request} # convert to generator common_bundle = (chunk for chunk in FAKE_COMMON_BUNDLE) get_bundle = Mock(return_value=common_bundle) loader = Mock(get_bundle=get_bundle) bundle_name = 'bundle_name' with patch('ui.templatetags.render_bundle.get_loader', return_value=loader) as get_loader: assert render_bundle(context, bundle_name) == ( '<script type="text/javascript" src="{base}/{filename}" >' '</script>'.format( base="/static/bundles", filename=FAKE_COMMON_BUNDLE[0]['name'], ) ) assert public_path(request) == "/static/bundles/" get_bundle.assert_called_with(bundle_name) get_loader.assert_called_with('DEFAULT')
def test_get_context_data_inheritance(self): class TestWizard(CookieWizardView): """ A subclass that implements ``get_context_data`` using the standard protocol for generic views (accept only **kwargs). See ticket #17148. """ def get_context_data(self, **kwargs): context = super(TestWizard, self).get_context_data(**kwargs) context['test_key'] = 'test_value' return context factory = RequestFactory() view = TestWizard.as_view([forms.Form]) response = view(factory.get('/')) self.assertEqual(response.context_data['test_key'], 'test_value')
def test_pdf_template_view_unicode(self, show_content=False): """Test PDFTemplateView with unicode content.""" view = UnicodeContentPDFTemplateView.as_view( filename=self.pdf_filename, show_content_in_browser=show_content, template_name=self.template ) # As PDF request = RequestFactory().get('/') response = view(request) self.assertEqual(response.status_code, 200) response.render() fileheader = self.attached_fileheader if show_content: fileheader = self.inline_fileheader self.assertEqual(response['Content-Disposition'], fileheader.format(self.pdf_filename)) # not sure how we can test this as the contents is all encoded... # best we can do for the moment is check it's a pdf and it worked. # self.assertTrue('?' in response.content) self.assertTrue(response.content.startswith(b'%PDF-')) self.assertTrue(response.content.endswith(b'%%EOF\n'))
def setUp(self, *args, **kwargs): super(LogSetupMiddlewareTest, self).setUp(*args, **kwargs) self.factory = RequestFactory() # LogSetupMiddleware only looks under this module logging_root = __name__ self.middleware = LogSetupMiddleware(root=logging_root) self.filter = RequestFilter(request=None) # Create test logger with a placeholder logger self.logger = logging.getLogger(__name__) self.logger.filters = [] self.logger.addFilter(self.filter) # Stub out original handlers self._original_handlers = logging._handlers self._original_handlerList = logging._handlerList logging._handlers = {} logging._handlerList = [] # Create test handler self.handler = logging.NullHandler() self.handler.filters = [] self.handler.addFilter(self.filter) self.logger.addHandler(self.handler)
def handle(self, *args, **options): request = RequestFactory().get("/") response = HttpResponse() user = User() n = 0 print(TEMPLATE_A) for pattern, age, cache_type, dc in rules: policy = POLICIES[cache_type] policy(request, response, user, age) if n == 0: print("if", end="") else: print("else if", end="") print(""" (req.url ~ "%s") {""" % pattern.pattern) print("""set req.http.Hash-Cookies = "%s";""" % response["X-Hash-Cookies"]) print("}") n += 1 print(TEMPLATE_B)
def setUp(self): self.factory = RequestFactory() self._patch_views('upsert_user') self._patch_views('process_email') self._patch_views('email_is_blocked') models.Newsletter.objects.create( slug='slug', title='title', active=False, languages='en-US,fr', vendor_id='VENDOR1', ) models.Newsletter.objects.create(slug='slug2', vendor_id='VENDOR2') models.Newsletter.objects.create(slug='slug3', vendor_id='VENDOR3') models.Newsletter.objects.create(slug='slug-private', vendor_id='VENDOR4', private=True)
def test_sort_from_request_ASC(self): """Should sort variants wrt. a specific column - string, int or float -, from smaller to bigger or in alphabetical order. Compare with manual sort. Frequencies could have None values, which is why we use this Sort. """ for field in ['chrom','start','aaf_1kg_all']: request = RequestFactory().get('', {'order_by': '{},ASC'.format(field)}) order = sort_from_request(request) self.assertIsInstance(order, Sort) self.assertEqual(order.key, field) self.assertEqual(order.reverse, False) var = self.variants.order_by(order.key, order.reverse) col0 = [getattr(v,field) for v in self.variants] col = [getattr(v,field) for v in var] col0_nonull = [x for x in col0 if x is not None] col0 = [None]*(len(col)-len(col0_nonull)) + sorted(col0_nonull) self.assertEqual(col0, col)
def test_genotypes_Nothing_filter_from_request_with_ss_from_request(self): """With a sound grouping passed by url.""" samples = [('samples', 'A=09818,09819'), ('samples', 'B=09960,09961')] filters = [('filter', 'genotype=nothing')] request = RequestFactory().get('', samples + filters) fc = variant_filters_from_request(request, db='test') self.assertIsInstance(fc, FiltersCollection) self.assertTrue(len(fc) == len(filters)) gf = fc['genotype'] self.assertEqual(sorted(gf.ss.groups.keys()), ['A','B']) self.assertEqual(gf.name, 'genotype') self.assertEqual(gf.val, 'nothing') self.assertEqual(gf.op, '=') self.assertIsInstance(gf, GenotypesFilterDoNothing) #@unittest.skip('')
def test_genotypes_Dominant_filter_from_request_with_ss_from_request(self): """With a sound grouping passed by url.""" samples = [('samples', 'not_affected=09960,09961'), ('samples', 'affected=09818,09819')] filters = [('filter', 'genotype=dominant')] request = RequestFactory().get('', samples + filters) fc = variant_filters_from_request(request, db='test') gf = fc['genotype'] self.assertIsInstance(gf, GenotypesFilterDominant) var = gf.apply(self.variants).variants for v in var: gts = self.genotypes[v.pk-1] self.assertGreater(gts[S09818], 1) self.assertGreater(gts[S09819], 1) self.assertEqual(gts[S09960], 1) self.assertEqual(gts[S09961], 1) ############################ # CONDITIONS MERGE # ############################
def test_variant_filters_from_request(self): filters = [('filter', 'in_dbsnp'), ('filter', 'quality<=1000'), ('filter', 'aaf_1kg_all<=0.5'), ('filter', 'aaf_max_all>0.4'), ] expected = [DbsnpFilter(name='in_dbsnp', op='=', val='1'), QualityFilter(name='quality', op='<=', val='1000'), ContinuousFilter(name='aaf_1kg_all', op='<=', val='0.5'), ContinuousFilter(name='aaf_max_all', op='>', val='0.4'), ] request = RequestFactory().get('', filters) fc = variant_filters_from_request(request, db='test') self.assertIsInstance(fc, FiltersCollection) self.assertTrue(len(fc) == len(filters)) def check(ff, expect): self.assertEqual(ff.val, expect.val) self.assertEqual(ff.name, expect.name) self.assertEqual(ff.op, expect.op) for f in expected: check(fc[f.name], f)
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)
def _test_signup_email_verified_externally(self, signup_email, verified_email): username = 'johndoe' request = RequestFactory().post(reverse('account_signup'), {'username': username, 'email': signup_email, 'password1': 'johndoe', 'password2': 'johndoe'}) # Fake stash_verified_email from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) request.user = AnonymousUser() request.session['account_verified_email'] = verified_email from .views import signup resp = signup(request) self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], get_adapter().get_login_redirect_url(request)) self.assertEqual(len(mail.outbox), 0) return get_user_model().objects.get(username=username)
def setUp(self): self.request = RequestFactory() self.request.COOKIES = {} middleware = SessionMiddleware() middleware.process_request(self.request) self.request.session.save() for prop, value in BASE_LTI_PARAMS.items(): self.request.session[prop] = value self.lti = LTI('initial', 'any') self.emptyRequest = RequestFactory() self.emptyRequest.COOKIES = {} middleware = SessionMiddleware() middleware.process_request(self.emptyRequest) self.emptyRequest.session.save()
def get_page_request(self, page, user, path=None, edit=False, lang_code='en', disable=False): path = path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang_code if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} if disable: request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None request.current_page = page mid = ToolbarMiddleware() mid.process_request(request) if hasattr(request,'toolbar'): request.toolbar.populate() return request
def test_as_dict(self): """ Tests that the correct dictionary shape is returned from the as_dict() function. """ distillery = Distillery.objects.get(pk=1) search_query = SearchQuery('test "more testing"') distillery_results = self._get_instance(search_query, distillery) factory = RequestFactory() request = factory.get('/api/v1/search/') self.assertDictEqual(distillery_results.as_dict(request), { 'count': 1, 'results': MOCK_RESULTS_LIST, 'next': None, 'previous': None, 'distillery': { 'id': 1, 'name': 'mongodb.test_database.test_posts', 'url': 'http://testserver/api/v1/distilleries/1/', } })
def test_as_dict(self): """ Tests that the as_dict() function returns the correct dictionary shape. """ search_query = SearchQuery('@source=test_database.test_posts test') distillery_results_list = self._get_instance(search_query) factory = RequestFactory() request = factory.get('/api/v1/search/') self.assertEqual(distillery_results_list.as_dict(request), { 'count': 1, 'results': [{ 'count': 1, 'next': None, 'previous': None, 'results': MOCK_RESULTS_LIST, 'distillery': { 'id': 1, 'name': 'mongodb.test_database.test_posts', 'url': 'http://testserver/api/v1/distilleries/1/', } }] })
def test_verify(self): rf = RequestFactory() signer = SecureAcceptanceSigner() # Baseline signer.secret_key = 'FOO' request = rf.post('/', { 'signed_field_names': 'foo,baz', 'signature': 'IVMC7Aj8pDKwLx+0eNfIfoQAHvViiLeavLyYatCtB+c=', 'foo': 'bar', 'baz': 'bat', }) self.assertTrue( signer.verify_request(request) ) # Bad signature given request = rf.post('/', { 'signed_field_names': 'foo,baz', 'signature': 'IVMC7Aj8pDKwLx+0eNfIfoQAHvViiLeavLyYatCtB', 'foo': 'bar', 'baz': 'bat', }) self.assertFalse( signer.verify_request(request) )
def test_get_combo_view_loads_from_disk(self): test_file_contents = factory.make_string() # Create a valid file with a proper extension (the combo loader only # serves JS or CSS files) test_file_name = "%s.js" % factory.make_string() test_file = self.make_file( name=test_file_name, contents=test_file_contents) directory = os.path.dirname(test_file) view = get_combo_view(directory) # Create a request for test file. rf = RequestFactory() request = rf.get("/test/?%s" % test_file_name) response = view(request) expected_content = '/* %s */\n%s\n' % ( test_file_name, test_file_contents) self.assertEqual( (http.client.OK, expected_content.encode( settings.DEFAULT_CHARSET)), (response.status_code, response.content))
def test_get_combo_redirects_if_unknown_type(self): # The optional parameter 'default_redirect' allows to configure # a default address where requests for files of unknown types will be # redirected. # Create a test file with an unknown extension. test_file_name = "%s.%s" % ( factory.make_string(), factory.make_string()) redirect_root = factory.make_string() view = get_combo_view( factory.make_string(), default_redirect=redirect_root) rf = RequestFactory() request = rf.get("/test/?%s" % test_file_name) response = view(request) self.assertEqual( '%s%s' % (redirect_root, test_file_name), extract_redirect(response)) # String used by convoy to replace missing files.
def test_preserves_query_string(self): view = SimpleListView.as_view( query_results=[SimpleFakeModel(i) for i in range(6)]) request = RequestFactory().get('/index?lookup=value') response = view(request) context = response.context_data self.assertEqual("", context["first_page_link"]) self.assertEqual("", context["previous_page_link"]) # Does this depend on dict hash values for order or does django sort? self.assertEqual( { "lookup": ["value"], "page": ["2"], }, parse_qs(urlparse(context["next_page_link"]).query)) self.assertEqual( { "lookup": ["value"], "page": ["3"], }, parse_qs(urlparse(context["last_page_link"]).query))
def setUp(self): super().setUp() self.req = RequestFactory().get("/") self.req.user = self.user
def test_get_initial(self): request = RequestFactory().get("/") view = self.get_instance(ContentCreateView, request=request) initial = view.get_initial() self.assertIsNone(initial.get("text")) view.request = RequestFactory().get("/?url=url&title=title¬es=notes&dummy=dummy") initial = view.get_initial() self.assertEqual(initial.get("text"), render_to_string("content/_bookmarklet_initial.html", { "title": "title", "notes": "notes", "url": "url", }))
def setUp(self): super(PageTitleTests, self).setUp() self.request = client.RequestFactory().get('fake')
def test_construct_get_query_get_and_params(): request = RequestFactory().get(reverse('dashboard:product-list')) context = {'request': request} result = construct_get_query(context, param1='param1', param2='param2', page='3') assert result.startswith('?') result = result[1:].split('&') assert 'param1=param1' in result assert 'param2=param2' in result assert 'page=3' in result
def test_construct_get_query_params(): request = RequestFactory().get(reverse('dashboard:product-list')) context = {'request': request} result = construct_get_query(context) assert result == ''
def test_paginate(): request = RequestFactory().get(reverse('dashboard:product-list')) context = {'request': request} result = paginate(context, 'page_obj') assert result['n_forward'] == 6 assert result['n_backward'] == -6 assert result['next_section'] == 11 assert result['previous_section'] == -11
def test_new_get_current_from_request(): factory = RequestFactory() request = factory.get(reverse('dashboard:site-index')) result = Site.objects.get_current(request) assert result.name == 'mirumee.com' assert result.domain == 'mirumee.com' assert type(result.settings) == SiteSettings assert str(result.settings) == 'mirumee.com'
def setUp(self): self.factory = RequestFactory()
def get_factory(self): return RequestFactory()
def setUp(self): self.rf = RequestFactory()