Ticket #4022: strict-headers-constructor-4022.patch

File strict-headers-constructor-4022.patch, 2.2 KB (added by rwall, 7 years ago)

Add validation for the addHeader value argument and refactor the setHeaders method to use it.

  • twisted/web/http_headers.py

    === modified file 'twisted/web/http_headers.py'
     
    66An API for storing HTTP header names and values.
    77"""
    88
    9 
     9import types
    1010from UserDict import DictMixin
    1111
    1212
     
    134134    """
    135135    _caseMappings = {'www-authenticate': 'WWW-Authenticate'}
    136136
    137     def __init__(self, rawHeaders=None):
     137    def __init__(self, rawHeaders={}):
    138138        self._rawHeaders = {}
    139         if rawHeaders is not None:
    140             for name, values in rawHeaders.iteritems():
    141                 self.setRawHeaders(name, values)
     139        for name, values in rawHeaders.iteritems():
     140            self.setRawHeaders(name, values)
    142141
    143142
    144143    def __repr__(self):
     
    196195
    197196        @return: C{None}
    198197        """
    199         self._rawHeaders[name.lower()] = values
     198        if isinstance(values, types.StringTypes):
     199            raise TypeError(
     200                'values must not be text. ' \
     201                'Got %s' % (type(values)))
     202
     203        self.removeHeader(name)
     204        for val in values:
     205            self.addRawHeader(name, val)
    200206
    201207
    202208    def addRawHeader(self, name, value):
     
    209215        @type value: C{str}
    210216        @param value: The value to set for the named header.
    211217        """
    212         values = self.getRawHeaders(name)
    213         if values is None:
    214             self.setRawHeaders(name, [value])
    215         else:
    216             values.append(value)
     218        self._rawHeaders.setdefault(name.lower(), []).append(value)
    217219
    218220
    219221    def getRawHeaders(self, name, default=None):
  • twisted/web/test/test_http_headers.py

    === modified file 'twisted/web/test/test_http_headers.py'
     
    3838        self.assertEqual(h.getRawHeaders("test"), rawValue)
    3939
    4040
     41    def test_setInvalidRawHeaders(self):
     42        """
     43        L{Headers.setRawHeaders} expects a sequence of string values.
     44        """
     45        h = Headers()
     46        self.assertRaises(TypeError, h.setRawHeaders, "test", "value1")
     47
     48
    4149    def test_addRawHeader(self):
    4250        """
    4351        L{Headers.addRawHeader} adds a new value for a given header.