Commits

mitsuhiko  committed 26f63d5

More tests :)

  • Participants
  • Parent commits 5e8c9a8

Comments (0)

Files changed (7)

File tests/test_datastructures.py

 from werkzeug.datastructures import FileStorage, MultiDict, \
      ImmutableMultiDict, CombinedMultiDict, ImmutableTypeConversionDict, \
      ImmutableDict, Headers, ImmutableList, EnvironHeaders, \
-     OrderedMultiDict, ImmutableOrderedMultiDict
+     OrderedMultiDict, ImmutableOrderedMultiDict, HeaderSet
 
 
 def test_multidict_pickle():
 
     assert sorted(d.items()) == [('bar', '2'), ('foo', '1')], d.items()
     assert sorted(d.items(multi=True)) == [('bar', '2'), ('bar', '3'), ('foo', '1')]
-
+    assert 'missingkey' not in d
+    assert 'foo' in d
 
     # type lookup
     assert d.get('foo', type=int) == 1
 
 
 def test_immutable_dict_copies_are_mutable():
-    for cls in ImmutableTypeConversionDict, ImmutableMultiDict, ImmutableDict:
+    for cls in ImmutableTypeConversionDict, ImmutableMultiDict, ImmutableDict, \
+               ImmutableOrderedMultiDict:
         immutable = cls({'a': 1})
         assert_raises(TypeError, immutable.pop, 'a')
 
     assert headers['x'] == r'y; z="\""'
 
     # defaults
-    headers = Headers({
-        'Content-Type': 'text/plain',
-        'X-Foo':        'bar',
-        'X-Bar':        ['1', '2']
-    })
+    headers = Headers([
+        ('Content-Type', 'text/plain'),
+        ('X-Foo',        'bar'),
+        ('X-Bar',        '1'),
+        ('X-Bar',        '2')
+    ])
     assert headers.getlist('x-bar') == ['1', '2']
     assert headers.get('x-Bar') == '1'
     assert headers.get('Content-Type') == 'text/plain'
     assert headers[:1] == Headers([('Content-Type', 'text/plain')])
     del headers[:2]
     del headers[-1]
-    assert headers == Headers([('X-Bar', '2')])
+    assert headers == Headers([('X-Bar', '1')])
 
     # copying
     a = Headers([('foo', 'bar')])
     assert headers.pop('b', 2) == 2
     assert_raises(KeyError, headers.pop, 'c')
 
+    # set replaces and accepts same arguments as add
+    a = Headers()
+    a.set('Content-Disposition', 'useless')
+    a.set('Content-Disposition', 'attachment', filename='foo')
+    assert a['Content-Disposition'] == 'attachment; filename=foo'
+
+
+def test_header_set():
+    """Test the header set"""
+    hs = HeaderSet()
+    hs.add('foo')
+    hs.add('bar')
+    assert 'Bar' in hs
+    assert hs.find('foo') == 0
+    assert hs.find('BAR') == 1
+    assert hs.find('baz') < 0
+    hs.discard('missing')
+    hs.discard('foo')
+    assert hs.find('foo') < 0
+    assert hs.find('bar') == 0
+    assert_raises(IndexError, hs.index, 'missing')
+    assert hs.index('bar') == 0
+    assert hs
+    hs.clear()
+    assert not hs
+
 
 def test_environ_headers_counts():
     """Ensure that the EnvironHeaders count correctly."""
     assert d.poplist('bar') == [42]
     assert not d
 
+    d.get('missingkey') is None
+
     d.add('foo', 42)
     d.add('foo', 23)
     d.add('bar', 2)
     d = EnvironHeaders({'HTTP_X_FOO': 'test'})
     assert_raises(TypeError, d.__delitem__, 0)
     assert_raises(TypeError, d.add, 42)
+    assert_raises(TypeError, d.pop, 'x-foo')
     assert_raises(TypeError, d.popitem)
     assert_raises(TypeError, d.setdefault, 'foo', 42)
     assert dict(d.items()) == {'X-Foo': 'test'}
+    assert_raises(TypeError, d.copy)

File tests/test_debug.py

-
 # -*- coding: utf-8 -*-
 """
     werkzeug.debug test

File tests/test_http.py

     assert unquote_etag('"foo"') == ('foo', False)
     assert unquote_etag('w/"foo"') == ('foo', True)
     es = parse_etags('"foo", "bar", w/"baz", blar')
+    assert sorted(es) == ['bar', 'blar', 'foo']
     assert 'foo' in es
     assert 'baz' not in es
     assert es.contains_weak('baz')

File werkzeug/datastructures.py

         return key, [x.value for x in buckets]
 
 
+def _options_header_vkw(value, kw):
+    if not kw:
+        return value
+    return dump_options_header(value, dict((k.replace('_', '-'), v)
+                                            for k, v in kw.items()))
+
+
 class Headers(object):
     """An object that stores some headers.  It has a dict-like interface
     but is ordered and can store the same keys multiple times.
         .. versionadded:: 0.4.1
             keyword arguments were added for :mod:`wsgiref` compatibility.
         """
-        if kw:
-            _value = dump_options_header(_value, dict((k.replace('_', '-'), v)
-                                                      for k, v in kw.items()))
-        self._list.append((_key, _value))
+        self._list.append((_key, _options_header_vkw(_value, kw)))
 
     def add_header(self, _key, _value, **_kw):
         """Add a new header tuple to the list.
         """Clears all headers."""
         del self._list[:]
 
-    def set(self, key, value):
+    def set(self, _key, _value, **kw):
         """Remove all header tuples for `key` and add a new one.  The newly
         added key either appears at the end of the list if there was no
         entry or replaces the first one.
 
+        Keyword arguments can specify additional parameters for the header
+        value, with underscores converted to dashes.  See :meth:`add` for
+        more information.
+
+        .. versionchanged:: 0.6.1
+           :meth:`set` now accepts the same arguments as :meth:`add`.
+
         :param key: The key to be inserted.
         :param value: The value to be inserted.
         """
-        lc_key = key.lower()
+        lc_key = _key.lower()
+        _value = _options_header_vkw(_value, kw)
         for idx, (old_key, old_value) in enumerate(self._list):
             if old_key.lower() == lc_key:
                 # replace first ocurrence
-                self._list[idx] = (key, value)
+                self._list[idx] = (_key, _value)
                 break
         else:
-            return self.add(key, value)
+            return self.add(_key, _value)
         self._list[idx + 1:] = [(k, v) for k, v in self._list[idx + 1:]
                                 if k.lower() != lc_key]
 

File werkzeug/exceptions.py

             if getattr(obj, 'code', None) is not None:
                 default_exceptions[obj.code] = obj
                 __all__.append(obj.__name__)
-        except TypeError:
+        except TypeError: # pragma: no cover
             continue
 _find_exceptions()
 del _find_exceptions

File werkzeug/http.py

 import inspect
 try:
     from email.utils import parsedate_tz
-except ImportError:
+except ImportError: # pragma: no cover
     from email.Utils import parsedate_tz
 from urllib2 import parse_http_list as _parse_list_header
 from datetime import datetime, timedelta
 try:
     from hashlib import md5
-except ImportError:
+except ImportError: # pragma: no cover
     from md5 import new as md5
 
 

File werkzeug/wrappers.py

            The `charset` parameter was deprecated and became a no-op.
         """
         # XXX: deprecated
-        if __debug__ and charset is not None:
+        if __debug__ and charset is not None: # pragma: no cover
             from warnings import warn
             warn(DeprecationWarning('charset was deprecated and is ignored.'),
                  stacklevel=2)
         self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
 
     @property
-    def header_list(self):
+    def header_list(self): # pragma: no cover
         # XXX: deprecated
         if __debug__:
             from warnings import warn