def test_widget_no_empty_option_without_placeholder_without_url(self): """Assert that it renders an empty option, if not given a url.""" class Form(forms.Form): test = forms.ChoiceField( choices=[(1, "A")], widget=Select2(), required=False ) form = Form(http.QueryDict()) expected = ''' <select data-autocomplete-light-function="select2" data-autocomplete-light-language="en-US" id="id_test" name="test"> <option value="1">A</option> </select> '''.strip() observed = six.text_type(form['test'].as_widget()) self.assertHTMLEqual(observed, expected) form = Form(http.QueryDict('test=1')) expected = ''' <select data-autocomplete-light-function="select2" data-autocomplete-light-language="en-US" id="id_test" name="test"> <option value="1" %s>A</option> </select> '''.strip() % selected_tag() observed = six.text_type(form['test'].as_widget()) self.assertHTMLEqual(observed, expected)
def _load_post_and_files(self): # Populates self._post and self._files if self.method == 'POST': if self.environ.get('CONTENT_TYPE', '').startswith('multipart'): self._raw_post_data = '' try: self._post, self._files = self.parse_file_upload( self.META, self.environ['wsgi.input']) except: # An error occured while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. self._post = http.QueryDict('') self._files = datastructures.MultiValueDict() # Mark that an error occured. This allows self.__repr__ to # be explicit about it instead of simply representing an # empty POST self._post_parse_error = True raise else: self._post, self._files = http.QueryDict( self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() else: self._post, self._files = http.QueryDict( '', encoding=self._encoding), datastructures.MultiValueDict()
def _load_post_and_files(self): # Populates self._post and self._files if self.method == 'POST': if self.environ.get('CONTENT_TYPE', '').startswith('multipart'): self._raw_post_data = '' self._post, self._files = self.parse_file_upload(self.META, self.environ['wsgi.input']) else: self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() else: self._post, self._files = http.QueryDict('', encoding=self._encoding), datastructures.MultiValueDict()
def delete(self, request, key): """Remove an email address, validated or not.""" request.DELETE = http.QueryDict(request.body) email_addr = request.DELETE.get('email') user_id = request.DELETE.get('user') if not email_addr: return http.HttpResponseBadRequest() try: email = EmailAddressValidation.objects.get(address=email_addr, user_id=user_id) except EmailAddressValidation.DoesNotExist: pass else: email.delete() return http.HttpResponse(status=204) try: email = EmailAddress.objects.get(address=email_addr, user_id=user_id) except EmailAddress.DoesNotExist: raise http.Http404 email.user = None email.save() return http.HttpResponse(status=204)
def changeset_list(request, repository_label): """A view listing the changesets for the given repository.""" repository_lookup = {'label': repository_label} if not request.user.is_authenticated(): repository_lookup['is_private'] = False repository = shortcuts.get_object_or_404(models.Repository, **repository_lookup) if request.GET.get('results', '').isdigit(): results = int(request.GET.get('results')) else: results = settings.SVNLIT_CHANGESETS_PER_PAGE qs = http.QueryDict('', mutable=True) qs.update(request.GET) if 'page' in qs: del qs['page'] qs = qs.urlencode() return list_detail.object_list(request, repository.changesets.all(), paginate_by=results, extra_context={ 'repository': repository, 'qs': qs }, template_object_name='changeset')
def as_request(self): assert self.request_data, 'Could not construct an empty TestCase object' request = http.HttpRequest() data = self.request_data_dict request.path = data['path'] request.method = data['method'] request.path_info = data['path_info'] request._body = data['body'] request.META = data['headers'] request._encoding = data['encoding'] request._stream = StringIO() request._read_started = False request._post_parse_error = False request.resolver_match = None request._load_post_and_files() query_string = '%s&%s=1' % (data['query_string'], TEST_REQUEST_PARAM) request.GET = http.QueryDict(query_string, encoding=request.encoding) request.POST = getattr(request, '_post') request.FILES = getattr(request, '_files') request.COOKIES = http.parse_cookie( request.META.get('HTTP_COOKIE', b'')) request.REQUEST = datastructures.MergeDict(request.POST, request.GET) # extra attributes added by middlewares from django.contrib.auth.middleware import get_user engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore( request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) request.user = SimpleLazyObject(lambda: get_user(request)) return request
def __init__(self, request=None, parent=None, **kw): self.request = request self.response = dict() if request is not None: if request.method in ('PUT', 'DELETE'): rqdata = http.QueryDict(request.body) # note that `body` was named `raw_post_data` before Django 1.4 #~ print 20130222, rqdata else: # rqdata = request.REQUEST rqdata = getattr(request, request.method) kw = self.parse_req(request, rqdata, **kw) if parent is not None: for k in inheritable_attrs: if k in kw: if kw[k] is None: raise Exception("%s : %s=None" % (kw, k)) else: kw[k] = getattr(parent, k) kv = kw.setdefault('known_values', {}) kv.update(parent.known_values) # kw.setdefault('user', parent.user) # kw.setdefault('subst_user', parent.subst_user) # kw.setdefault('renderer', parent.renderer) # kw.setdefault('requesting_panel', parent.requesting_panel) self.setup(**kw)
def _load_post_and_files(self): # Populates self._post and self._files if self.method == 'POST': if self.environ.get('CONTENT_TYPE', '').startswith('multipart'): header_dict = dict([(k, v) for k, v in self.environ.items() if k.startswith('HTTP_')]) header_dict['Content-Type'] = self.environ.get( 'CONTENT_TYPE', '') self._post, self._files = http.parse_file_upload( header_dict, self.raw_post_data) else: self._post, self._files = http.QueryDict( self.raw_post_data), datastructures.MultiValueDict() else: self._post, self._files = http.QueryDict( ''), datastructures.MultiValueDict()
def test_change_password_sets_logout_reason(self): self.mock_user_update_own_password.return_value = None self.mock_user_get.return_value = mock.Mock(options={}) formData = { 'method': 'PasswordForm', 'current_password': '******', 'new_password': '******', 'confirm_password': '******' } res = self.client.post(INDEX_URL, formData, follow=False) self.assertRedirectsNoFollow(res, settings.LOGOUT_URL) self.assertIn('logout_reason', res.cookies) self.assertIn('logout_status', res.cookies) self.assertEqual(res.cookies['logout_reason'].value, "Password changed. Please log in again to continue.") self.assertEqual('success', res.cookies['logout_status'].value) scheme, netloc, path, query, fragment = urlsplit(res.url) redirect_response = res.client.get(path, http.QueryDict(query)) self.assertRedirectsNoFollow(redirect_response, settings.LOGIN_URL) self.mock_user_get.assert_called_once_with(test.IsHttpRequest(), '1', admin=False) self.mock_user_update_own_password.assert_called_once_with( test.IsHttpRequest(), 'oldpwd', 'normalpwd')
def test_get_with_fields(self, from_client_input): """ Test the GET search handler with fields in the request. """ class FakeSearchView(search.SearchView): model = mock.MagicMock() request = mock.MagicMock() request.GET = http.QueryDict('field=name&field=id&filters={"name":"admin"}') from_client_input.return_value = {} view = FakeSearchView() view.model.SERIALIZER.return_value.data = [{'serialized': 'content'}] with mock.patch.object(FakeSearchView, '_generate_response', side_effect=FakeSearchView._generate_response) as _generate_response: results = view.get(request) self.assertEqual(type(results), http.HttpResponse) self.assertEqual(results.content, '[{"serialized": "content"}]') self.assertEqual(results.status_code, 200) _generate_response.assert_called_once_with( {'fields': ['name', 'id'], 'filters': {'name': 'admin'}}, {}) from_client_input.assert_called_once_with( {'fields': ['name', 'id'], 'filters': {"name": "admin"}})
def test_get_no_query_params(self, from_client_input): """ Test the GET search handler without any parameters passed. """ class FakeSearchView(search.SearchView): model = mock.MagicMock() del model.SERIALIZER request = mock.MagicMock() request.GET = http.QueryDict('') view = FakeSearchView() FakeSearchView.model.objects.find_by_criteria.return_value = [ 'big money', 'bigger money' ] with mock.patch.object(FakeSearchView, '_generate_response', side_effect=FakeSearchView._generate_response ) as _generate_response: results = view.get(request) self.assertEqual(type(results), http.HttpResponse) self.assertEqual(results.content, '["big money", "bigger money"]') self.assertEqual(results.status_code, 200) _generate_response.assert_called_once_with({}, {}) from_client_input.assert_called_once_with({})
def test_widget(self): form_class = None if not hasattr(self, 'get_widget_tests'): return for test in self.get_widget_tests(): if 'form_class' in test.keys(): form_class = test['form_class'] # for display test['form_class'] = form_class.__name__ form = form_class(http.QueryDict(test['fixture'])) try: valid = form.is_valid() except TypeError: print(self.__class__, test, self.get_widget_tests()) raise self.assertEqual( valid, test['expected_valid'], 'Unexepected valid: %s for test %s %s' % (valid, self.__class__.__name__, test)) if valid: data = form.cleaned_data['x'] self.assertEqual( text_type(data), text_type(test['expected_data']), 'Unexepected data: %s for test %s %s' % (data, self.__class__.__name__, test))
def _callback_url(request, is_success): status = is_success and 'success' or 'error' signed_notice = request.POST['signed_notice'] statsd.incr('purchase.payment_{0}_callback.received'.format(status)) # This is currently only used by Bango and Zippy. # Future providers should probably get added to the notification # abstraction in provider/views.py provider = ProviderHelper.choose() if provider.is_callback_token_valid(signed_notice): statsd.incr('purchase.payment_{0}_callback.ok'.format(status)) log.info('Callback {0} token was valid.'.format(status)) querystring = http.QueryDict(signed_notice) if 'ext_transaction_id' in querystring: ext_transaction_id = querystring['ext_transaction_id'] if is_success: tasks.payment_notify.delay(ext_transaction_id) else: tasks.chargeback_notify.delay(ext_transaction_id) return http.HttpResponse(status=204) else: statsd.incr('purchase.payment_{0}_callback.incomplete' ''.format(status)) log.error('Callback {0} token was incomplete: ' '{1}'.format(status, querystring)) else: statsd.incr('purchase.payment_{0}_callback.fail'.format(status)) log.error('Callback {0} token was invalid: ' '{1}'.format(status, signed_notice)) return http.HttpResponseBadRequest()
def wrapper(request, *args, **kwargs): # Dynamic resources based on a ConfigEntity instance need to pass the config_entity__id so that we can properly construct the dynamic resource if hasattr(self.Meta, 'abstract') and self.Meta.abstract: wrapped_view = self.subclass_resource_if_needed(view, request) # During the subclassing process we may have removed parameters needed only to resolve # the dynamic Resource class. We don't want those parameters to be used by the dynamic # resource for filtering filter = getattr(request, '_filters', request.GET) # request.GET is used for filtering along with kwargs['GET']. They are combined (see get_object_list) encoding = request.GET.encoding request._original_params = request.GET.copy() # Make sure the values are singular so we don't # get weird array values back request.GET = http.QueryDict( '&'.join( map_dict(lambda key, value: '%s=%s' % (key, value[-1] if isinstance(value, list) else value), filter) ), encoding=encoding ) else: wrapped_view = super(ModelResource, self).wrap_view(view) return wrapped_view(request, *args, **kwargs)
def _check_resp_auth(self, privkey, return_url, challenge, location, additional_fields=None): """Check that the response has the right authorization result""" self.assertTrue(location.startswith(return_url + '?'), "unexpected Location header: %r" % location) query_params = http.QueryDict(location[len(return_url) + 1:]) # Compute expected auth check_str = '1%s%s' % (challenge, privkey) known_resp_fields = set(('auth', )) if additional_fields: known_resp_fields.update(additional_fields) for field in self.client_simple.data_fields.split(','): self.assertTrue(field in query_params, "missing field %r in response" % field) check_str += query_params[field] known_resp_fields.add(field) check_str += '1' expected_auth = hashlib.md5(check_str.encode('utf-8')).hexdigest() self.assertEqual(known_resp_fields, set(query_params.keys()), "unexpected fields in response") return query_params, expected_auth
def test_parse_args_preserves_false(self): args = http.QueryDict('', mutable=True) args['opt_bool'] = False params, options = self.fake_search._parse_args(args) self.assertTrue(options['opt_bool'] is False)
def test_form(self): tests = ( { 'fixture': 'name=foo&related=%s-%s' % (self.group_ctype.pk, self.bluesmen.pk), 'valid': True, 'result': [self.bluesmen], }, { 'fixture': 'name=foo&related=%s-%s&related=%s-%s' % (self.group_ctype.pk, self.rockers.pk, self.user_ctype.pk, self.james.pk), 'valid': True, 'result': [self.james, self.rockers], }, ) instance = None for test in tests: form = FormMock(http.QueryDict(test['fixture']), instance=instance) self.assertEqual(form.is_valid(), test['valid']) instance = form.save() self.assertEqual(instance.related.all().generic_objects(), test['result'])
def make_url(self, request, return_url=None): """Compute the remote URL. Args: request: http.HttpRequest, the request to use for session storage and current URL retrieving return_url: str, the optional return URL to use; if empty, the current URL of the request will be used. Returns: the new url. """ challenge = hashlib.sha1(b''.join( struct.pack(b'B', random.randrange(0, 256)) for i in range(64))) challenge = challenge.hexdigest() request.session['authgroupex-challenge'] = challenge sig = hashlib.md5( (challenge + self.config.KEY).encode('ascii')).hexdigest() query = http.QueryDict('', mutable=True) query['challenge'] = challenge query['pass'] = sig query['url'] = request.build_absolute_uri(return_url) if self.config.GROUP: query['group'] = self.config.GROUP endpoint = self.config.ENDPOINT if self.config.FAKE: endpoint = reverse(endpoint) url = endpoint + '?' + query.urlencode() return url
def delete(self, request, app_label=None, actor=None, pk=None): data = http.QueryDict(request.body) ar = action_request( app_label, actor, request, data, False, renderer=settings.SITE.kernel.extjs_renderer) ar.set_selected_pks(pk) return settings.SITE.kernel.run_action(ar)
def request2data(request, user_language=None): if request.method == 'GET': rqdata = request.GET elif request.method in ('PUT', 'DELETE'): # raw_post_data before Django 1.4 rqdata = http.QueryDict(request.body) elif request.method == 'POST': rqdata = request.POST else: # e.g. OPTIONS, HEAD if user_language and len(settings.SITE.languages) > 1: translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() # ~ logger.info("20121205 on_login %r",translation.get_language()) request.requesting_panel = None request.subst_user = None return # ~ else: # DELETE # ~ request.subst_user = None # ~ request.requesting_panel = None # ~ return request.requesting_panel = rqdata.get(constants.URL_PARAM_REQUESTING_PANEL, None) if len(settings.SITE.languages) > 1: user_language = rqdata.get(constants.URL_PARAM_USER_LANGUAGE, user_language) if user_language: translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() return rqdata
def test_get_with_json_field(self, from_client_input): """ Test the GET search handler with a json field. This covers `filters` as well as `sort`. """ class FakeSearchView(search.SearchView): model = mock.MagicMock() del model.SERIALIZER request = mock.MagicMock() request.GET = http.QueryDict('filters={"name":"admin"}') view = FakeSearchView() FakeSearchView.model.objects.find_by_criteria.return_value = [ 'big money', 'bigger money' ] with mock.patch.object(FakeSearchView, '_generate_response', side_effect=FakeSearchView._generate_response ) as _generate_response: results = view.get(request) self.assertEqual(type(results), http.HttpResponse) self.assertEqual(results.content, '["big money", "bigger money"]') self.assertEqual(results.status_code, 200) _generate_response.assert_called_once_with( {'filters': { "name": "admin" }}, {}) from_client_input.assert_called_once_with( {'filters': { "name": "admin" }})
def put(self, request, app_label=None, actor=None): rpt = requested_actor(app_label, actor) PUT = http.QueryDict(request.body) # raw_post_data before Django 1.4 gc = dict( widths=[int(x) for x in PUT.getlist(constants.URL_PARAM_WIDTHS)], columns=[str(x) for x in PUT.getlist(constants.URL_PARAM_COLUMNS)], hiddens=[(x == 'true') for x in PUT.getlist(constants.URL_PARAM_HIDDENS)], #~ hidden_cols=[str(x) for x in PUT.getlist('hidden_cols')], ) filter = PUT.get('filter', None) if filter is not None: filter = json.loads(filter) gc['filters'] = [constants.dict2kw(flt) for flt in filter] name = PUT.get('name', None) if name is None: name = constants.DEFAULT_GC_NAME else: name = int(name) gc.update(label=PUT.get('label', "Standard")) try: msg = rpt.save_grid_config(name, gc) except IOError as e: msg = _("Error while saving GC for %(table)s: %(error)s") % dict( table=rpt, error=e) return settings.SITE.kernel.error(None, msg, alert=True) #~ logger.info(msg) settings.SITE.kernel.extjs_renderer.build_site_cache(True) return settings.SITE.kernel.success(msg)
def test_create_with_relation(self): form = self.model_form_class( http.QueryDict('name=test&%s' % self.form_value(self.janis))) self.assertTrue(form.is_valid()) result = form.save() self.assertEqual(self.field_value(result), self.janis)
def put(self, request, app_label=None, actor=None, pk=None): data = http.QueryDict(request.body) # raw_post_data before Django 1.4 # logger.info("20150130 %s", data) ar = action_request( app_label, actor, request, data, False, renderer=settings.SITE.kernel.extjs_renderer) ar.set_selected_pks(pk) return settings.SITE.kernel.run_action(ar)
def put(self, request, app_label=None, actor=None, pk=None): data = http.QueryDict(request.body) # raw_post_data before Django 1.4 # print("20180712 ApiElement.put() %s" % data) ar = action_request( app_label, actor, request, data, False, renderer=settings.SITE.kernel.extjs_renderer) ar.set_selected_pks(pk) return settings.SITE.kernel.run_action(ar)
def _get_get(self): if not hasattr(self, '_get'): # The WSGI spec says 'QUERY_STRING' may be absent. raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '') self._get = http.QueryDict(raw_query_string, encoding=self._encoding) return self._get
def on_login(self, request, user): """The method which is applied when the user has been determined. On multilingual sites, if URL_PARAM_USER_LANGUAGE is present it overrides user.language. """ # logger.info("20130923 on_login(%s)" % user) request.user = user user_language = user.language # or settings.SITE.get_default_language() if settings.USE_TZ: activate(user.timezone or settings.TIME_ZONE) if request.method == 'GET': rqdata = request.GET elif request.method in ('PUT', 'DELETE'): # raw_post_data before Django 1.4 rqdata = http.QueryDict(request.body) elif request.method == 'POST': rqdata = request.POST else: # e.g. OPTIONS, HEAD if len(settings.SITE.languages) > 1: if user_language: translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() #~ logger.info("20121205 on_login %r",translation.get_language()) request.requesting_panel = None request.subst_user = None return # ~ else: # DELETE #~ request.subst_user = None #~ request.requesting_panel = None #~ return if len(settings.SITE.languages) > 1: user_language = rqdata.get(constants.URL_PARAM_USER_LANGUAGE, user_language) if user_language: translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() su = rqdata.get(constants.URL_PARAM_SUBST_USER, None) if su is not None: if su: try: su = settings.SITE.user_model.objects.get(id=int(su)) #~ logger.info("20120714 su is %s",su.username) except settings.SITE.user_model.DoesNotExist: su = None else: su = None # e.g. when it was an empty string "su=" request.subst_user = su request.requesting_panel = rqdata.get( constants.URL_PARAM_REQUESTING_PANEL, None)
def test_get_with_invalid_filters(self, mock_parse): """ InvalidValue should be raised if param 'filters' is not json. """ mock_parse.return_value = ({'mock': 'query'}, 'tuple') search_view = search.SearchView() mock_request = mock.MagicMock() mock_request.GET = http.QueryDict('filters=invalid json') self.assertRaises(exceptions.InvalidValue, search_view.get, mock_request)
def test_add_relation(self): form = self.model_form_class(http.QueryDict( 'name=test&%s' % self.form_value(self.janis)), instance=self.test_instance) self.assertTrue(form.is_valid()) result = form.save() self.assertEqual(self.field_value(result), self.janis)
def test_validate(self): fixture = self.model.objects.create(name=self.id()) form = self.form( http.QueryDict('name=%s&test=%s' % (self.id(), fixture.pk))) form.fields['test'].queryset = self.tag.objects.exclude(pk=fixture.pk) self.assertFalse(form.is_valid())