# HG changeset patch # User Guillaume Vandevelde # Date 1581350162 -3600 # Node ID cc71a801b846eba9b4da1decddbd447283272ab2 # Parent 9fa65579520f0c2dba413cfa791e0419fbd6105e [utils] Add the possibility to add elements in the head of an UStringIO list diff -r 9fa65579520f -r cc71a801b846 cubicweb/test/unittest_utils.py --- a/cubicweb/test/unittest_utils.py Tue Aug 27 20:16:01 2019 +0200 +++ b/cubicweb/test/unittest_utils.py Mon Feb 10 16:56:02 2020 +0100 @@ -287,6 +287,9 @@ head.add_js(base_url + u'bob1.js') head.add_js(u'http://ext.com/bob2.js') head.add_js(u'http://ext.com/bob3.js') + head.write_front( + '' + ) head.add_css(base_url + u'bob4.css') head.add_css(base_url + u'bob5.css') head.add_css(base_url + u'bob6.css', 'print') @@ -295,6 +298,7 @@ head.add_ie_css(base_url + u'bob9.css', 'print', u'[if lt IE 7]') result = head.getvalue() expected = u""" + diff -r 9fa65579520f -r cc71a801b846 cubicweb/utils.py --- a/cubicweb/utils.py Tue Aug 27 20:16:01 2019 +0200 +++ b/cubicweb/utils.py Mon Feb 10 16:56:02 2020 +0100 @@ -33,6 +33,7 @@ from inspect import getfullargspec as getargspec else: from inspect import getargspec +from functools import wraps from itertools import repeat from uuid import uuid4 from warnings import warn @@ -191,6 +192,22 @@ self._size -= 1 +def handle_writing_constraints(method): + @wraps(method) + def wrapper(self, value): + assert isinstance(value, text_type), u"unicode required not %s : %s"\ + % (type(value).__name__, repr(value)) + if self.tracewrites: + from traceback import format_stack + stack = format_stack(None)[:-1] + escaped_stack = xml_escape(json_dumps(u'\n'.join(stack))) + escaped_html = xml_escape(value).replace('\n', '
\n') + tpl = u'%s' + value = tpl % (escaped_stack, escaped_html) + return method(self, value) + return wrapper + + class UStringIO(list): """a file wrapper which automatically encode unicode string to an encoding specifed in the constructor @@ -205,18 +222,14 @@ __nonzero__ = __bool__ + @handle_writing_constraints def write(self, value): - assert isinstance(value, text_type), u"unicode required not %s : %s"\ - % (type(value).__name__, repr(value)) - if self.tracewrites: - from traceback import format_stack - stack = format_stack(None)[:-1] - escaped_stack = xml_escape(json_dumps(u'\n'.join(stack))) - escaped_html = xml_escape(value).replace('\n', '
\n') - tpl = u'%s' - value = tpl % (escaped_stack, escaped_html) self.append(value) + @handle_writing_constraints + def write_front(self, value): + self.insert(0, value) + def getvalue(self): return u''.join(self)