internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pallets/werkzeug

Issue:
Headers.__delitem__ signature incompatible with ImmutableHeadersMixin.__delitem__
[Mypy](https://github.com/python/mypy) recently introduced stricter checks for function signature compatibility (https://github.com/python/mypy/pull/2521). Since `werkzeug` is included in the typeshed library with typing stubs, it found an issue with the signatures of `__delitem__()` in datastructure.py. Consider:
```py3
class Headers(Mapping):
  def __delitem__(self, key, _index_operation=True): ...
```
vs.
```py3
class ImmutableHeadersMixin(object):
  def __delitem__(self, key): ...

class EnvironHeaders(ImmutableHeadersMixin, Headers): ...
```

Basically, it's invalid to replace `__delitem__()` accepting an optional kwarg with an implementation that doesn't.


Discussion:
@ambv Am I correct that changing the signature of `ImmutableHeadersMixin.__delitem__` to accept arbitrary args would work?
Yes, that would work. `__delitem__()` in the *immutable* mixin is supposed to be a no-op so it's reasonable for it to accept (and ignore) arbitrary arguments.

To rephrase the problem for future reference:
* When you're using `Headers` directly, you can pass `_index_operation=True` to `__delitem__()`. Remember, the "user" of this functionality might be the class itself.
* `EnvironHeaders` is a subclass of `Headers` so it should accept `_index_operation=True`, too, but it doesn't because `ImmutableHeadersMixin` comes in first in the MRO.
It sounds to me that the correct fix would be to rename `Headers.__delitem__` and add a new `__delitem__` implementation that just calls the renamed method with default arguments.

Resolving patch:
diff --git a/werkzeug/datastructures.py b/werkzeug/datastructures.py
--- a/werkzeug/datastructures.py
+++ b/werkzeug/datastructures.py
@@ -1301,7 +1301,7 @@ class ImmutableHeadersMixin(object):
     :private:
     """
 
-    def __delitem__(self, key):
+    def __delitem__(self, key, **kwargs):
         is_immutable(self)
 
     def __setitem__(self, key, value):


Test patch:
Repository: pallets/werkzeug

Issue:
Allow CombinedMultiDict.copy()
`CombinedMultiDict` is immutable, but does not have a `.copy()` method to get a mutable copy from it. It would be quite useful.



Discussion:
I believe you may be looking for the [`.to_dict()`](https://github.com/pallets/werkzeug/blob/ff82fa21297294804e8d1c3203074fec4d292d1d/werkzeug/datastructures.py#L1434) method, which will return a standard python dictionary with the `CombinedMultiDict` contents.

Well I was thinking on getting a mutable MultiDict, with all its api

Would passing the returned dictionary to an instantiation of `MultiDict` work for your use case? Otherwise, you'd end up writing a `.copy()`/`.to_dict()` method equivalent for every possible output type.

e.g.

```
 foo = MultiDict([('foo', 'bar')])
 baz = MultiDict([('baz', 'qux')])

 immut_dict = CombinedMultiDict([foo, baz])
 mut_dict = MultiDict(immut_dict.to_dict()) 
```

Yes, that would work indeed. Or creating a `MultiDict` and updating it with the others instead of creating a `CombinedMultiDict` directly. My suggestion was just for an enhacement to allow to do that more easily, just like with `ImmutableMultiDict`, but you can close it if you consider it not necessary.

It's not clear what the behavior should be. `Combined` is a view of other dicts, what it returns changes as the underlying dicts change. Making a copy would break that expectation. Then again, the current `copy` seems pretty useless. I'm leaning towards changing to `return MultiDict(self)`, but I'll wait a bit.

Resolving patch:
diff --git a/werkzeug/datastructures.py b/werkzeug/datastructures.py
--- a/werkzeug/datastructures.py
+++ b/werkzeug/datastructures.py
@@ -1478,8 +1478,16 @@ def listvalues(self):
         return (x[1] for x in self.lists())
 
     def copy(self):
-        """Return a shallow copy of this object."""
-        return self.__class__(self.dicts[:])
+        """Return a shallow mutable copy of this object.
+
+        This returns a :class:`MultiDict` representing the data at the
+        time of copying. The copy will no longer reflect changes to the
+        wrapped dicts.
+
+        .. versionchanged:: 0.15
+            Return a mutable :class:`MultiDict`.
+        """
+        return MultiDict(self)
 
     def to_dict(self, flat=True):
         """Return the contents as regular dict.  If `flat` is `True` the


Test patch:
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py
--- a/tests/test_datastructures.py
+++ b/tests/test_datastructures.py
@@ -613,10 +613,9 @@ def test_basic_interface(self):
         with pytest.raises(TypeError):
             d['foo'] = 'blub'
 
-        # copies are immutable
+        # copies are mutable
         d = d.copy()
-        with pytest.raises(TypeError):
-            d['foo'] = 'blub'
+        d['foo'] = 'blub'
 
         # make sure lists merges
         md1 = datastructures.MultiDict((("foo", "bar"),))
Repository: pallets/werkzeug

Issue:
MultiPartParser's start_file_streaming in formparser.py could pass arguments by keywords to stream_factory
As pointed out by this comment https://github.com/pallets/werkzeug/pull/1180#issuecomment-349267532, line https://github.com/pallets/werkzeug/blob/master/werkzeug/formparser.py#L362 can reference to default_stream_factory. The argument order being passed is incorrect:
`(total_content_length, content_type, filename, content_length)` vs `(total_content_length, filename, content_type, content_length)`.

I suggest same fix to be done as in the mentioned pull request by passing as keyword arguments instead of positional argument.


Discussion:

Resolving patch:
diff --git a/src/werkzeug/formparser.py b/src/werkzeug/formparser.py
--- a/src/werkzeug/formparser.py
+++ b/src/werkzeug/formparser.py
@@ -401,7 +401,10 @@ def start_file_streaming(self, filename, headers, total_content_length):
         except (KeyError, ValueError):
             content_length = 0
         container = self.stream_factory(
-            total_content_length, content_type, filename, content_length
+            total_content_length=total_content_length,
+            filename=filename,
+            content_type=content_type,
+            content_length=content_length,
         )
         return filename, container
 
diff --git a/src/werkzeug/wrappers/base_request.py b/src/werkzeug/wrappers/base_request.py
--- a/src/werkzeug/wrappers/base_request.py
+++ b/src/werkzeug/wrappers/base_request.py
@@ -263,8 +263,8 @@ def _get_file_stream(
         """
         return default_stream_factory(
             total_content_length=total_content_length,
-            content_type=content_type,
             filename=filename,
+            content_type=content_type,
             content_length=content_length,
         )
 


Test patch:
Repository: pallets/werkzeug

Issue:
Drop Python 3.4 support
EOL 2019-03-19: https://devguide.python.org/#status-of-python-branches


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -36,7 +36,6 @@
         "Programming Language :: Python :: 2",
         "Programming Language :: Python :: 2.7",
         "Programming Language :: Python :: 3",
-        "Programming Language :: Python :: 3.4",
         "Programming Language :: Python :: 3.5",
         "Programming Language :: Python :: 3.6",
         "Programming Language :: Python :: 3.7",


Test patch:
Repository: pallets/werkzeug

Issue:
Change to Unauthorized's argument order breaks existing code
In this commit: https://github.com/pallets/werkzeug/pull/1319/files#diff-43a63db82587e91732eda181306d76c7R240

The constructor of `Unauthorized` used to take the `description` as the first argument, but now takes `www_authenticate` as the first argument. This breaks backwards compatibility with all existing callers of `Unauthorized`. 

Would it be possible to change:
```py
def __init__(self, www_authenticate=None, description=None):
```

to
```py
def __init__(self, description=None, www_authenticate=None):
```

In 0.14.x, `abort(401, 'some error description')` now does a completely different thing in 0.15.0 - and that is a breaking change. 

`405 - MethodNotAllowed` also shares this special case... but that's 11 years old at this point :\ 


Discussion:
Same issue here.
It is an important breaking change, I have to fix the `Werkzeug` version to `0.14.1` in my `setup.py` by waiting a fix
Thanks for your help
I guess I was trying to be consistent with 405, but yeah, it makes more sense to leave description first.

Resolving patch:
diff --git a/src/werkzeug/exceptions.py b/src/werkzeug/exceptions.py
--- a/src/werkzeug/exceptions.py
+++ b/src/werkzeug/exceptions.py
@@ -246,10 +246,18 @@ class Unauthorized(HTTPException):
     response is invalid if it doesn't provide at least one value for
     this header, although real clients typically don't care.
 
-    :param www-authenticate: A single value, or list of values, for the
-        WWW-Authenticate header.
     :param description: Override the default message used for the body
         of the response.
+    :param www-authenticate: A single value, or list of values, for the
+        WWW-Authenticate header.
+
+    .. versionchanged:: 0.15.1
+        ``description`` was moved back as the first argument, restoring
+         its previous position.
+
+    .. versionchanged:: 0.15.0
+        ``www_authenticate`` was added as the first argument, ahead of
+        ``description``.
     """
 
     code = 401
@@ -260,7 +268,7 @@ class Unauthorized(HTTPException):
         " how to supply the credentials required."
     )
 
-    def __init__(self, www_authenticate=None, description=None):
+    def __init__(self, description=None, www_authenticate=None):
         HTTPException.__init__(self, description)
         if not isinstance(www_authenticate, (tuple, list)):
             www_authenticate = (www_authenticate,)


Test patch:
Repository: pallets/werkzeug

Issue:
Double-printing text in django runserver_plus
On a Django project using `django_extensions`, using `python manage.py runserver_plus` with the latest `werkzeug` (`v0.15.1`) results in double-printing all logging statements. This is not an issue in `v0.14.1`; the issue arose in commit 4cf77d2. The reason for this issue is that `runserver_plus` modifies the `werkzeug` logger by setting its log level and adding a handler. Older versions of `werkzeug` only added a log handler if there was no log level *and* no handler on the root logger. Since that commit, `werkzeug` adds a log handler if there is no handler on the root logger, regardless of log level. This results in there being two handlers, and thus all logging statements get printed twice. If `werkzeug` checks for a handler on the `werkzeug` logger instead of the root logger, the second handler won't get added. Is there a reason to check the root logger for handlers, seeing as `werkzeug` doesn't use the root logger?


Discussion:
See #1407 cc @ramnes 
Needs the same level check as pallets/flask#2436.

Resolving patch:
diff --git a/src/werkzeug/_internal.py b/src/werkzeug/_internal.py
--- a/src/werkzeug/_internal.py
+++ b/src/werkzeug/_internal.py
@@ -9,6 +9,7 @@
     :license: BSD-3-Clause
 """
 import inspect
+import logging
 import re
 import string
 from datetime import date
@@ -80,20 +81,44 @@ def _get_environ(obj):
     return env
 
 
+def _has_level_handler(logger):
+    """Check if there is a handler in the logging chain that will handle
+    the given logger's effective level.
+    """
+    level = logger.getEffectiveLevel()
+    current = logger
+
+    while current:
+        if any(handler.level <= level for handler in current.handlers):
+            return True
+
+        if not current.propagate:
+            break
+
+        current = current.parent
+
+    return False
+
+
 def _log(type, message, *args, **kwargs):
-    """Log into the internal werkzeug logger."""
+    """Log a message to the 'werkzeug' logger.
+
+    The logger is created the first time it is needed. If there is no
+    level set, it is set to :data:`logging.INFO`. If there is no handler
+    for the logger's effective level, a :class:`logging.StreamHandler`
+    is added.
+    """
     global _logger
-    if _logger is None:
-        import logging
 
+    if _logger is None:
         _logger = logging.getLogger("werkzeug")
+
         if _logger.level == logging.NOTSET:
             _logger.setLevel(logging.INFO)
-        # Only set up a default log handler if the
-        # end-user application didn't set anything up.
-        if not logging.root.handlers:
-            handler = logging.StreamHandler()
-            _logger.addHandler(handler)
+
+        if not _has_level_handler(_logger):
+            _logger.addHandler(logging.StreamHandler())
+
     getattr(_logger, type)(message.rstrip(), *args, **kwargs)
 
 


Test patch:
Repository: pallets/werkzeug

Issue:
ProfilerMiddleware Missing in Latest Release
### Environment

```
$ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.14.4
BuildVersion:	18E226

$ python --version
Python 3.7.3

$ pip freeze
Werkzeug==0.15.2
```

### Observed Behavior
Inability to import the ProfilerMiddleware from werkzeug as described in [the documentation](https://werkzeug.palletsprojects.com/en/0.15.x/middleware/profiler/)

```
>>> from werkzeug.middleware.profile import ProfilerMiddleware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'werkzeug.middleware.profile'
```

### Steps to Reproduce
```
[~/git] $ mkdir test_venv
[~/git] $ cd test_venv/
[~/git/test_venv] $ python3 -m venv venv
[~/git/test_venv] $ source venv/bin/activate
(venv) [~/git/test_venv] $ pip --version
pip 19.0.3 from /Users/cchapline/git/test_venv/venv/lib/python3.7/site-packages/pip (python 3.7)
(venv) [~/git/test_venv] $ pip install werkzeug
Collecting werkzeug
  Using cached https://files.pythonhosted.org/packages/18/79/84f02539cc181cdbf5ff5a41b9f52cae870b6f632767e43ba6ac70132e92/Werkzeug-0.15.2-py2.py3-none-any.whl
Installing collected packages: werkzeug
Successfully installed werkzeug-0.15.2
(venv) [~/git/test_venv] $ python
Python 3.7.3 (default, Apr  4 2019, 10:56:22)
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from werkzeug.middleware.profile import ProfilerMiddleware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'werkzeug.middleware.profile'
>>> import werkzeug.middleware as mw
>>> dir(mw)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'dispatcher', 'http_proxy', 'shared_data']
```

### Expected Behavior

The `ImportError` should not occur as I can see the code in `site-packages`:

```
(venv) [~/git/test_venv] $ ls venv/lib/python3.7/site-packages/werkzeug/middleware/profiler.py
venv/lib/python3.7/site-packages/werkzeug/middleware/profiler.py
```


Discussion:

Resolving patch:
diff --git a/src/werkzeug/middleware/profiler.py b/src/werkzeug/middleware/profiler.py
--- a/src/werkzeug/middleware/profiler.py
+++ b/src/werkzeug/middleware/profiler.py
@@ -56,7 +56,7 @@ class ProfilerMiddleware(object):
 
     .. code-block:: python
 
-        from werkzeug.middleware.profile import ProfilerMiddleware
+        from werkzeug.middleware.profiler import ProfilerMiddleware
         app = ProfilerMiddleware(app)
 
     .. versionchanged:: 0.15


Test patch:
Repository: pallets/werkzeug

Issue:
Failing style check for B011 and B009
When running style check, the following error occurs:

```
B011 Do not call assert False since python -O removes these calls. Instead callers should raise AssertionError().
src/werkzeug/debug/__init__.py:144:42: B009 Do not call getattr with a constant attribute value, it is not any safer than normal property access.
src/werkzeug/debug/__init__.py:161:34: B009 Do not call getattr with a constant attribute value, it is not any safer than normal property access.
```


Discussion:

Resolving patch:
diff --git a/src/werkzeug/debug/__init__.py b/src/werkzeug/debug/__init__.py
--- a/src/werkzeug/debug/__init__.py
+++ b/src/werkzeug/debug/__init__.py
@@ -156,7 +156,7 @@ def get_pin_and_cookie_name(app):
         else:
             num = pin
 
-    modname = getattr(app, "__module__", getattr(app.__class__, "__module__"))
+    modname = getattr(app, "__module__", app.__class__.__module__)
 
     try:
         # getuser imports the pwd module, which does not exist in Google
@@ -173,7 +173,7 @@ def get_pin_and_cookie_name(app):
     probably_public_bits = [
         username,
         modname,
-        getattr(app, "__name__", getattr(app.__class__, "__name__")),
+        getattr(app, "__name__", app.__class__.__name__),
         getattr(mod, "__file__", None),
     ]
 


Test patch:
diff --git a/tests/contrib/test_wrappers.py b/tests/contrib/test_wrappers.py
--- a/tests/contrib/test_wrappers.py
+++ b/tests/contrib/test_wrappers.py
@@ -85,4 +85,4 @@ class MyResponse(wrappers.DynamicCharsetResponseMixin, Response):
     except TypeError:
         pass
     else:
-        assert False, "expected type error on charset setting without ct"
+        raise AssertionError("expected type error on charset setting without ct")
diff --git a/tests/test_test.py b/tests/test_test.py
--- a/tests/test_test.py
+++ b/tests/test_test.py
@@ -56,7 +56,7 @@ def redirect_with_get_app(environ, start_response):
         "http://localhost/first/request",
         "http://localhost/some/redirect/",
     ):
-        assert False, 'redirect_demo_app() did not expect URL "%s"' % req.url
+        raise AssertionError('redirect_demo_app() did not expect URL "%s"' % req.url)
     if "/some/redirect" not in req.url:
         response = redirect("http://localhost/some/redirect/")
     else:
Repository: pallets/werkzeug

Issue:
Switch from termcolor to click
Change the optional dependency for terminal colors to Click. Should be part of #1234.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -54,7 +54,6 @@
     python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
     extras_require={
         "watchdog": ["watchdog"],
-        "termcolor": ["termcolor"],
         "dev": [
             "pytest",
             "coverage",
diff --git a/src/werkzeug/serving.py b/src/werkzeug/serving.py
--- a/src/werkzeug/serving.py
+++ b/src/werkzeug/serving.py
@@ -72,9 +72,9 @@ def __getattr__(self, name):
     ssl = _SslDummy()
 
 try:
-    import termcolor
+    import click
 except ImportError:
-    termcolor = None
+    click = None
 
 
 def _get_openssl_crypto_module():
@@ -392,23 +392,23 @@ def log_request(self, code="-", size="-"):
 
         code = str(code)
 
-        if termcolor:
-            color = termcolor.colored
+        if click:
+            color = click.style
 
             if code[0] == "1":  # 1xx - Informational
-                msg = color(msg, attrs=["bold"])
+                msg = color(msg, bold=True)
             elif code[0] == "2":  # 2xx - Success
-                msg = color(msg, color="white")
+                msg = color(msg, fg="white")
             elif code == "304":  # 304 - Resource Not Modified
-                msg = color(msg, color="cyan")
+                msg = color(msg, fg="cyan")
             elif code[0] == "3":  # 3xx - Redirection
-                msg = color(msg, color="green")
+                msg = color(msg, fg="green")
             elif code == "404":  # 404 - Resource Not Found
-                msg = color(msg, color="yellow")
+                msg = color(msg, fg="yellow")
             elif code[0] == "4":  # 4xx - Client Error
-                msg = color(msg, color="red", attrs=["bold"])
+                msg = color(msg, fg="red", bold=True)
             else:  # 5xx, or any other response
-                msg = color(msg, color="magenta", attrs=["bold"])
+                msg = color(msg, fg="magenta", bold=True)
 
         self.log("info", '"%s" %s %s', msg, code, size)
 


Test patch:
Repository: pallets/werkzeug

Issue:
ProfilerMiddleware's default filename_format causes ValueError when ProfilerMiddleware is used with profile_dir
## Environment

```
$ sw_vers 
ProductName:	Mac OS X
ProductVersion:	10.13.6
BuildVersion:	17G3025

$ python --version
Python 3.7.2

$ pip freeze
Click==7.0
Flask==1.0.2
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
Werkzeug==0.15.2
```

Basically, the only Python dependency I installed was Flask because that's what I'm most familiar with. However, the error I'm describing looks to be contained within werkzeug.


## Observed Behavior

When using `ProfilerMiddleware` with its `profile_dir` argument, the following error gets raised after a request is sent to the server:

```
Error on request:
Traceback (most recent call last):
  File "/dev/jlove-bazaarvoice/werkzeug-profiler-bug/.venv/lib/python3.7/site-packages/werkzeug/serving.py", line 302, in run_wsgi
    execute(self.server.app)
  File "/dev/jlove-bazaarvoice/werkzeug-profiler-bug/.venv/lib/python3.7/site-packages/werkzeug/serving.py", line 290, in execute
    application_iter = app(environ, start_response)
  File "/dev/jlove-bazaarvoice/werkzeug-profiler-bug/.venv/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/dev/jlove-bazaarvoice/werkzeug-profiler-bug/.venv/lib/python3.7/site-packages/werkzeug/middleware/profiler.py", line 119, in __call__
    time=time.time(),
ValueError: Unknown format code 'd' for object of type 'float'
```

## Expected Behavior

No `ValueError`.

## Steps to Reproduce

1. `pip install flask`
2. Save the following file as app.py.
```python
# app.py
from flask import Flask
from werkzeug.middleware.profiler import ProfilerMiddleware

app = Flask(__name__)
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=".")


@app.route("/", methods=["GET"])
def get_index():
    return "Hello, world!"
```
3. Start the server with `FLASK_APP=app.py flask run`.
4. Send a request to the server (e.g. http://127.0.0.1:5000/).

## Workaround/Solution

Slightly modify `ProfilerMiddleware`'s `filename_format`, replacing the `d` with `f`. For example:
```python
app.wsgi_app = ProfilerMiddleware(
    app.wsgi_app, profile_dir=".", filename_format="{method}.{path}.{elapsed:06f}ms.{time:f}.prof"
)
```

Both instances of `d` need to be replaced because both `elapsed` and `time` are floating point numbers.


Discussion:

Resolving patch:
diff --git a/src/werkzeug/middleware/profiler.py b/src/werkzeug/middleware/profiler.py
--- a/src/werkzeug/middleware/profiler.py
+++ b/src/werkzeug/middleware/profiler.py
@@ -77,7 +77,7 @@ def __init__(
         sort_by=("time", "calls"),
         restrictions=(),
         profile_dir=None,
-        filename_format="{method}.{path}.{elapsed:06d}ms.{time:d}.prof",
+        filename_format="{method}.{path}.{elapsed:.0f}ms.{time:.0f}.prof",
     ):
         self._app = app
         self._stream = stream


Test patch: