def test_best_matches(): accept = Accept('Content-Type', 'text/html, foo/bar') assert accept.best_matches() == ['text/html', 'foo/bar'] accept = Accept('Content-Type', 'text/html, foo/bar;q=0.5') assert accept.best_matches() == ['text/html', 'foo/bar'] accept = Accept('Content-Type', 'text/html;q=0.5, foo/bar') assert accept.best_matches() == ['foo/bar', 'text/html']
def test_best_match_with_complex_q(): accept = Accept('text/html, foo/bar;q=0.55, baz/gort;q=0.59') assert accept.best_match(['text/html', 'foo/bar']) == 'text/html' accept = Accept('text/html;q=0.5, foo/bar;q=0.586, baz/gort;q=0.5966') assert "baz/gort;q=0.597" in str(accept) assert "foo/bar;q=0.586" in str(accept) assert "text/html;q=0.5" in str(accept) assert accept.best_match(['text/html', 'baz/gort']) == 'baz/gort'
def test_best_matches_with_fallback(): accept = Accept('Content-Type', 'text/html, foo/bar') assert accept.best_matches('xxx/yyy') == ['text/html', 'foo/bar', 'xxx/yyy'] accept = Accept('Content-Type', 'text/html;q=0.5, foo/bar') assert accept.best_matches('xxx/yyy') == ['foo/bar', 'text/html', 'xxx/yyy'] assert accept.best_matches('foo/bar') == ['foo/bar'] assert accept.best_matches('text/html') == ['foo/bar', 'text/html']
def generate_response(self, environ, start_response): if self.content_length is not None: del self.content_length headerlist = list(self.headerlist) accept_value = environ.get('HTTP_ACCEPT', '') accept = Accept(accept_value) match = accept.best_match( ['application/json', 'text/html', 'text/plain'], default_match='text/plain') if match == 'text/html': content_type = 'text/html' body = self.html_body(environ) elif match == 'application/json': content_type = 'application/json' body = self.json_body(environ) else: content_type = 'text/plain' body = self.plain_body(environ) extra_kw = {} if isinstance(body, text_type): extra_kw.update(charset='utf-8') resp = Response(body, status=self.status, headerlist=headerlist, content_type=content_type, **extra_kw) resp.content_type = content_type return resp(environ, start_response)
def test_accept_repr(): name, value = ('Content-Type', 'text/html') accept = Accept(name, value) assert repr(accept) == '<%s at 0x%x %s: %s>' % ('Accept', abs(id(accept)), name, str(accept))
def create_dummy_request(additional_settings={}, *args, **kargs): from c2cgeoportal.pyramid_ import default_user_validator request = tests.create_dummy_request( { "mapserverproxy": { "default_ogc_server": "__test_ogc_server", "external_ogc_server": "__test_external_ogc_server", }, "functionalities": { "registered": {}, "anonymous": {}, "available_in_templates": [] }, "layers": { "geometry_validation": True } }, *args, **kargs) request.accept_language = Accept("fr-CH,fr;q=0.8,en;q=0.5,en-US;q=0.3") request.registry.settings.update(additional_settings) request.headers["Host"] = host request.user = None request.interface_name = "main" request.registry.validate_user = default_user_validator request.client_addr = None return request
def test_init_accept_accept_charset(): name, value = ('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8') accept = Accept(name, value) assert accept.header_name == name assert accept.header_value == value assert accept._parsed == [('iso-8859-5', 1), ('unicode-1-1', 0.80000000000000004), ('iso-8859-1', 1)]
def test_accept_match(): accept = Accept('Content-Type', 'text/html') #FIXME: Accept._match should be standalone function _match that is # attached as Accept._match during Accept.__init__. assert accept._match('*', 'text/html') assert accept._match('text/html', 'text/html') assert accept._match('TEXT/HTML', 'text/html') assert not accept._match('foo/bar', 'text/html')
def test_best_match(): accept = Accept('text/html, foo/bar') assert accept.best_match(['text/html', 'foo/bar']) == 'text/html' assert accept.best_match(['foo/bar', 'text/html']) == 'foo/bar' assert accept.best_match([('foo/bar', 0.5), 'text/html']) == 'text/html' assert accept.best_match([('foo/bar', 0.5), ('text/html', 0.4)]) == 'foo/bar' assert_raises(ValueError, accept.best_match, ['text/*'])
def test_init_accept_accept_language(): name, value = ('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7') accept = Accept(name, value) assert accept.header_name == name assert accept.header_value == value assert accept._parsed == [('da', 1), ('en-gb', 0.80000000000000004), ('en', 0.69999999999999996)]
def test_doesnt_compress_too_small(self): request = pretend.stub(accept_encoding=Accept("gzip")) response = Response(body=b"foo") compressor(request, response) assert response.content_encoding is None assert response.content_length == 3 assert response.body == b"foo"
def test_accept_add_other_list_of_tuples(): accept = Accept('text/html') accept += [('foo/bar', 1)] assert str(accept) == 'text/html, foo/bar' accept += [('bar/baz', 0.5)] assert str(accept) == 'text/html, foo/bar, bar/baz;q=0.5' accept += ['she/bangs', 'the/house'] assert str(accept) == ('text/html, foo/bar, bar/baz;q=0.5, ' 'she/bangs, the/house')
def lookup_template_engine(self, tgl): """Return the template engine data. Provides a convenience method to get the proper engine, content_type, template, and exclude_names for a particular tg_format (which is pulled off of the request headers). """ request = tgl.request response = tgl.response try: render_custom_format = request._render_custom_format[ self.controller] except: render_custom_format = self.render_custom_format if render_custom_format: (content_type, engine, template, exclude_names, render_params) = self.custom_engines[render_custom_format] else: if self.default_engine: content_type = self.default_engine elif self.engines: if request._response_type and request._response_type in self.engines: accept_types = request._response_type else: accept_types = request.headers.get('accept', '*/*') content_type = Accept(accept_types).best_match( self.engines_keys, self.engines_keys[0]) else: content_type = 'text/html' # check for overridden content type from the controller call try: controller_content_type = response.headers['Content-Type'] # make sure we handle content_types like 'text/html; charset=utf-8' content_type = controller_content_type.split(';')[0] except KeyError: pass # check for overridden templates try: cnt_override_mapping = request._override_mapping[ self.controller] engine, template, exclude_names, render_params = cnt_override_mapping[ content_type.split(";")[0]] except (AttributeError, KeyError): (engine, template, exclude_names, render_params) = self.engines.get(content_type, (None, ) * 4) if 'charset' not in content_type and ( content_type.startswith('text') or content_type in ('application/xhtml+xml', 'application/xml', 'application/json')): content_type += '; charset=utf-8' return content_type, engine, template, exclude_names, render_params
def test_accept_match_lang(): accept = Accept('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7') #FIXME: Accept._match_lang should be standalone function _match_lang # that is attached as Accept._match during Accept.__init__. assert accept._match('*', 'da') assert accept._match('da', 'DA') assert accept._match('en', 'en-gb') assert accept._match('en-gb', 'en-gb') assert not accept._match('en-gb', 'fr-fr')
def test_nil_add(): nilaccept = NilAccept() accept = Accept('text/html') assert nilaccept + accept is accept new_accept = nilaccept + nilaccept assert isinstance(new_accept, accept.__class__) assert new_accept.header_value == '' new_accept = nilaccept + 'foo' assert isinstance(new_accept, accept.__class__) assert new_accept.header_value == 'foo'
def test_first_match(): accept = Accept('Content-Type', 'text/html, foo/bar') assert accept.first_match(['text/html', 'foo/bar']) == 'text/html' assert accept.first_match(['foo/bar', 'text/html']) == 'foo/bar' assert accept.first_match(['xxx/xxx', 'text/html']) == 'text/html' assert accept.first_match(['xxx/xxx']) == 'xxx/xxx' assert accept.first_match([None, 'text/html']) is None assert accept.first_match(['text/html', None]) == 'text/html' assert accept.first_match(['foo/bar', None]) == 'foo/bar' assert_raises(ValueError, accept.first_match, [])
def test_unknown_laguage(self): from pyramid.httpexceptions import HTTPInternalServerError from c2cgeoportal.views.fulltextsearch import FullTextSearchView from webob.acceptparse import Accept request = self._create_dummy_request() request.registry.settings["default_locale_name"] = "it" request.accept_language = Accept("es") fts = FullTextSearchView(request) response = fts.fulltextsearch() self.assertTrue(isinstance(response, HTTPInternalServerError))
def test_nil_add(): nilaccept = NilAccept('Connection-Close') accept = Accept('Content-Type', 'text/html') assert nilaccept + accept is accept new_accept = nilaccept + nilaccept assert isinstance(new_accept, accept.__class__) assert new_accept.header_name == 'Connection-Close' assert new_accept.header_value == '' new_accept = nilaccept + 'foo' assert isinstance(new_accept, accept.__class__) assert new_accept.header_name == 'Connection-Close' assert new_accept.header_value == 'foo'
def test_compresses_streaming(self): decompressed_body = b"foofoofoofoofoofoofoofoofoofoofoofoofoofoo" compressed_body = b"".join(list(gzip_app_iter([decompressed_body]))) request = pretend.stub(accept_encoding=Accept("gzip")) response = Response(app_iter=iter([decompressed_body])) compressor(request, response) assert response.content_encoding == "gzip" assert response.content_length is None assert response.body == compressed_body
def _purge_old(self): """ Delete any task on DB that has been completed for more than 3 days """ query_param = '{"literal":"(now()-finished_at) > \'P0Y0M3DT0H0M0S\'"}' url = self.base_url + '?$$=' + query_param params = {'$$': query_param} request = DummyRequest(path=url, params=params) request.method = 'DELETE' from webob.acceptparse import Accept request.accept = Accept("application/json") request.matchdict = {'base': self.basename} doc_view = DocumentCustomView(DocumentContextFactory(request), request) response = doc_view.delete_collection()
def create_dummy_request(additional_settings=None, authentication=True, user=None, *args, **kargs): if additional_settings is None: additional_settings = {} from c2cgeoportal_geoportal import default_user_validator from c2cgeoportal_geoportal import create_get_user_from_request from c2cgeoportal_geoportal.lib.authentication import create_authentication request = tests.create_dummy_request( { "host_forward_host": [], "mapserverproxy": { "default_ogc_server": "__test_ogc_server", "external_ogc_server": "__test_external_ogc_server", }, "functionalities": { "registered": {}, "anonymous": {}, "available_in_templates": [] }, "layers": { "geometry_validation": True } }, *args, **kargs) request.accept_language = Accept("fr-CH,fr;q=0.8,en;q=0.5,en-US;q=0.3") request.registry.settings.update(additional_settings) request.referer = "http://example.com/app" request.path_info_peek = lambda: "main" request.interface_name = "main" request.get_user = _get_user request.registry.validate_user = default_user_validator request.client_addr = None request.c2c_request_id = 'test' if authentication and user is None: request._get_authentication_policy = lambda: create_authentication( { "authtkt_cookie_name": "__test", "authtkt_secret": "123", }) elif user is not None: config.testing_securitypolicy(user) request.set_property(create_get_user_from_request( {"authorized_referers": [request.referer]}), name="user", reify=True) return request
def lookup_template_engine(self, tgl): """Return the template engine data. Provides a convenience method to get the proper engine, content_type, template, and exclude_names for a particular tg_format (which is pulled off of the request headers). """ request = tgl.request response = tgl.response try: render_custom_format = request._render_custom_format[ self.controller] except: render_custom_format = self.render_custom_format if render_custom_format: (content_type, engine, template, exclude_names, render_params) = self.custom_engines[render_custom_format] else: if self.default_engine: content_type = self.default_engine elif self.engines: if response.content_type is not None: # Check for overridden content type from the controller call accept_types = response.content_type elif request._response_type and request._response_type in self.engines: # Check for content type detected by request extensions accept_types = request._response_type else: accept_types = request.headers.get('accept', '*/*') content_type = Accept(accept_types).best_match( self.engines_keys, self.engines_keys[0]) else: content_type = 'text/html' # check for overridden templates try: cnt_override_mapping = request._override_mapping[ self.controller] engine, template, exclude_names, render_params = cnt_override_mapping[ content_type.split(";")[0]] except (AttributeError, KeyError): (engine, template, exclude_names, render_params) = self.engines.get(content_type, (None, ) * 4) return content_type, engine, template, exclude_names, render_params
def test_compresses_non_streaming(self): decompressed_body = b"foofoofoofoofoofoofoofoofoofoofoofoofoofoo" compressed_body = b"".join(list(gzip_app_iter([decompressed_body]))) request = pretend.stub(accept_encoding=Accept("gzip")) response = Response(body=decompressed_body) response.md5_etag() original_etag = response.etag compressor(request, response) assert response.content_encoding == "gzip" assert response.content_length == len(compressed_body) assert response.body == compressed_body assert response.etag != original_etag
def concept(request, lccn): concept = get_object_or_404(m.Concept, lccn=lccn) host = request.get_host() accept = Accept('Accept', request.META.get('HTTP_ACCEPT', 'text/html')) best_match = accept.best_match(['text/html', 'application/rdf+xml']) if best_match == 'application/rdf+xml': r = concept_rdf(request, lccn) else: alt_labels = concept.alternate_labels.all().order_by('text') broader = concept.broader.all().order_by('pref_label') extra_broader = concept.extra_broader() narrower = concept.narrower.all().order_by('pref_label') related = concept.related.all().order_by('pref_label') r = render_to_response('concept.html', dictionary=locals(), context_instance=RequestContext(request)) # let downstream caches know that the resonse can vary depending # on the Accept header that the client sent r['Vary'] = 'Accept' return r
def test_accept_add_other_accept(): accept = Accept('text/html') + Accept('foo/bar') assert str(accept) == 'text/html, foo/bar' accept += Accept('bar/baz;q=0.5') assert str(accept) == 'text/html, foo/bar, bar/baz;q=0.5'
def test_accept_str_with_q_not_1_multiple(): value = 'text/html;q=0.5, foo/bar' accept = Accept(value) assert str(accept) == value
def test_accept_str_with_q_not_1(): value = 'text/html;q=0.5' accept = Accept(value) assert str(accept) == value
def test_zero_quality(): assert Accept('bar, *;q=0').best_match(['foo']) is None assert 'foo' not in Accept('*;q=0')
def test_accept_str(): accept = Accept('text/html') assert str(accept) == 'text/html'
def test_accept_repr(): accept = Accept('text/html') assert repr(accept) == "<Accept('text/html')>"