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

Issue:
is_resource_modified() should work for methods besides GET
https://github.com/pallets/werkzeug/blob/5444a6f2c373064bb138447af0be2d72e0fa6b86/werkzeug/http.py#L893-L894

If the request method is post, but I want to return a different file every time, then this should not return false.


Discussion:
I agree. E.g. CalDAV and CardDAV use `If-None-Match` headers on PUT requests to prevent data-loss and avoid overwriting changed resources. I think the whole if-clause should be removed.

See #615. For 1.0 we should just change the default for the new parameter to `()`.

EDIT: Just reverted the fix, a similar check is done in `Request.make_conditional`. I don't think introducing such an ugly API is worth it, postponing everything to 1.0.

@untitaker If you can remember, what did you have in mind for a 1.0 fix? Just allow all methods? I'm trying to read through RFC 7232 now.
@davidism I think that was my intention but I am not sure if that's a good idea anymore.
My edit looks like I saw an issue with it and just postponed the decisioo to 1.0 without really knowing what to do
As far as I can tell from the RFC the change to check `is_resource_modified` on all methods would have been correct. Setting the headers only happens on GET, but responding to them them can happen with any method.

Resolving patch:
diff --git a/src/werkzeug/http.py b/src/werkzeug/http.py
--- a/src/werkzeug/http.py
+++ b/src/werkzeug/http.py
@@ -967,13 +967,14 @@ def is_resource_modified(
     :param ignore_if_range: If `False`, `If-Range` header will be taken into
                             account.
     :return: `True` if the resource was modified, otherwise `False`.
+
+    .. versionchanged:: 1.0.0
+        The check is run for methods other than ``GET`` and ``HEAD``.
     """
     if etag is None and data is not None:
         etag = generate_etag(data)
     elif data is not None:
         raise TypeError("both data and etag given")
-    if environ["REQUEST_METHOD"] not in ("GET", "HEAD"):
-        return False
 
     unmodified = False
     if isinstance(last_modified, string_types):


Test patch:
diff --git a/tests/test_http.py b/tests/test_http.py
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -386,9 +386,9 @@ def test_dump_header(self):
     def test_is_resource_modified(self):
         env = create_environ()
 
-        # ignore POST
+        # any method is allowed
         env["REQUEST_METHOD"] = "POST"
-        assert not http.is_resource_modified(env, etag="testing")
+        assert http.is_resource_modified(env, etag="testing")
         env["REQUEST_METHOD"] = "GET"
 
         # etagify from data
Repository: pallets/werkzeug

Issue:
Support Cache-Control extensions
I'm thinking specifically about https://bitsup.blogspot.fr/2016/05/cache-control-immutable.html.
Maybe add a dict str -> (str or None) which maps the extension name to the optional payload?


Discussion:
@mitsuhiko and other maintainers, would you accept a PR implementing [Cache-Control: Immutable](https://hacks.mozilla.org/2017/01/using-immutable-caching-to-speed-up-the-web/) (via e.g. `response.cache_control.immutable = True`)?
This is still marked experimental on MDN, I'm not sure I want to add that yet. Werkzeug already provides the tools to include whatever experimental options you want:

```python
# cache_control is also a dict
# None means set for bool options
response.cache_control["immutable"] = None

# or add the property
from werkzeug.datastructures import ResponseCacheControl, cache_property

ResponseCacheControl.immutable = cache_property("immutable", None, bool)
response.cache_control.immutable = True
```

Resolving patch:
diff --git a/src/werkzeug/datastructures.py b/src/werkzeug/datastructures.py
--- a/src/werkzeug/datastructures.py
+++ b/src/werkzeug/datastructures.py
@@ -2050,7 +2050,6 @@ class RequestCacheControl(ImmutableDictMixin, _CacheControl):
 
     max_stale = cache_property("max-stale", "*", int)
     min_fresh = cache_property("min-fresh", "*", int)
-    no_transform = cache_property("no-transform", None, None)
     only_if_cached = cache_property("only-if-cached", None, bool)
 
 
@@ -2074,6 +2073,7 @@ class ResponseCacheControl(_CacheControl):
     must_revalidate = cache_property("must-revalidate", None, bool)
     proxy_revalidate = cache_property("proxy-revalidate", None, bool)
     s_maxage = cache_property("s-maxage", None, None)
+    immutable = cache_property("immutable", None, bool)
 
 
 # attach cache_property to the _CacheControl as staticmethod


Test patch:
Repository: pallets/werkzeug

Issue:
Sort order is not stable in Accept class
```py
    from werkzeug.datastructures import LanguageAccept
    from werkzeug.http import parse_accept_header

    a = parse_accept_header("en-US,fr-FR", LanguageAccept)
    assert a.best == "en-US"  # fails, it returns fr-FR
```

I expected the order to be preserved. 

RFC 3282 describes desired behavior for Accept-Language: "If no Q values are given, the language-ranges are given in priority order, with the leftmost language-range being the most preferred language; this is an extension to the HTTP/1.1 rules, but matches current practice."

Looking at the source code, the Accept class is reverse-sorting the input list by specificity, then quality, then name; I think it should not sort by name and instead should preserve the given order.


Discussion:
According to current standard which is [RFC 7231](https://www.rfc-editor.org/rfc/rfc7231.html#section-5.3.5) I'd rather expect a list in case of equal preference matches. There is a note there describing this exact case.



Resolving patch:
diff --git a/src/werkzeug/datastructures.py b/src/werkzeug/datastructures.py
--- a/src/werkzeug/datastructures.py
+++ b/src/werkzeug/datastructures.py
@@ -1743,6 +1743,12 @@ class Accept(ImmutableList):
 
     .. versionchanged:: 0.5
        :class:`Accept` objects are forced immutable now.
+
+    .. versionchanged:: 1.0.0
+       :class:`Accept` internal values are no longer ordered
+       alphabetically for equal quality tags. Instead the initial
+       order is preserved.
+
     """
 
     def __init__(self, values=()):
@@ -1755,9 +1761,7 @@ def __init__(self, values=()):
         else:
             self.provided = True
             values = sorted(
-                values,
-                key=lambda x: (self._specificity(x[0]), x[1], x[0]),
-                reverse=True,
+                values, key=lambda x: (self._specificity(x[0]), x[1]), reverse=True,
             )
             list.__init__(self, values)
 


Test patch:
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py
--- a/tests/test_datastructures.py
+++ b/tests/test_datastructures.py
@@ -1126,6 +1126,10 @@ def test_accept_wildcard_specificity(self):
         assert accept.best_match(["asterisk", "times"], default=None) == "times"
         assert accept.best_match(["asterisk"], default=None) is None
 
+    def test_accept_equal_quality(self):
+        accept = self.storage_class([("a", 1), ("b", 1)])
+        assert accept.best == "a"
+
 
 class TestMIMEAccept(object):
     @pytest.mark.parametrize(
diff --git a/tests/test_wrappers.py b/tests/test_wrappers.py
--- a/tests/test_wrappers.py
+++ b/tests/test_wrappers.py
@@ -438,9 +438,9 @@ def test_accept_mixin():
     assert request.accept_mimetypes == MIMEAccept(
         [
             ("text/xml", 1),
-            ("image/png", 1),
             ("application/xml", 1),
             ("application/xhtml+xml", 1),
+            ("image/png", 1),
             ("text/html", 0.9),
             ("text/plain", 0.8),
             ("*/*", 0.5),
Repository: pallets/werkzeug

Issue:
routing.RequestRedirect.get_response : environ parameter is required
I tried out the generic HTTPException handler described in:
 https://flask.palletsprojects.com/en/1.1.x/errorhandling/#generic-exception-handlers

this handler calls get_response() without parameter on the error, but it breaks on a RequestRedirect as the environ parameter is required.

Is there a reason why RequestRedirect does not conform to the HTTPException signature for get_response ?

I think 
```    
def get_response(self, environ):
    return redirect(self.new_url, self.code)
```
should be replaced by 
```    
def get_response(self, environ=None):
    return redirect(self.new_url, self.code)
```


Discussion:

Resolving patch:
diff --git a/src/werkzeug/routing.py b/src/werkzeug/routing.py
--- a/src/werkzeug/routing.py
+++ b/src/werkzeug/routing.py
@@ -250,7 +250,7 @@ def __init__(self, new_url):
         RoutingException.__init__(self, new_url)
         self.new_url = new_url
 
-    def get_response(self, environ):
+    def get_response(self, environ=None):
         return redirect(self.new_url, self.code)
 
 


Test patch:
Repository: pallets/werkzeug

Issue:
Pytest fails due to missing dependency
Reproduction:

Activate virtualenv and execute `pytest` 

Expected result:
Tests are run

Actual result:
```(env) :~/git/werkzeug[master ?]🙂 pytest
========================= test session starts ==========================
platform darwin -- Python 3.6.8, pytest-5.3.2, py-1.8.0, pluggy-0.13.0
rootdir: /Users/latham/git/werkzeug, inifile: setup.cfg, testpaths: tests
plugins: mock-1.11.2, cov-2.8.1
collected 563 items / 1 error / 562 selected                           

================================ ERRORS ================================
_________________ ERROR collecting tests/test_debug.py _________________
tests/test_debug.py:372: in <module>
    @pytest.mark.timeout(2)
../../Library/Python/3.6/lib/python/site-packages/_pytest/mark/structures.py:327: in __getattr__
    PytestUnknownMarkWarning,
E   pytest.PytestUnknownMarkWarning: Unknown pytest.mark.timeout - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/latest/mark.html
!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!
=========================== 1 error in 1.60s ===========================```



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -57,6 +57,7 @@
         "watchdog": ["watchdog"],
         "dev": [
             "pytest",
+            "pytest-timeout",
             "coverage",
             "tox",
             "sphinx",


Test patch:
Repository: pallets/werkzeug

Issue:
Change in 1.0.0 to add pathlib support for `.save()` breaks usage of `io.BytesIO`
## Versions

* Python 3.7
* Werkzeug 1.0.0 (from PyPI)

## Report

The addition of pathlib support to `.save()` from #1654 breaks the the ability to pass `io.BytesIO` objects to `.save()`.

Previous behavior: Saving to an `io.BytesIO` object worked as expected.
Behavior in 1.0.0: An exception is thrown in `fspath()`.

```
  File "/app/main.py", line 310, in extract_metadata
    files['metadata'].save(metadata_io)
  File "/app/.venv/lib/python3.7/site-packages/werkzeug/datastructures.py", line 3061, in save
    dst = fspath(dst)
TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
```


Discussion:
Exact same issue here. Thumbed up.
For now I'm using this workaround

```python
# until https://github.com/pallets/werkzeug/issues/1733 is fixed
buf = io.BytesIO()
#request.files['photo'].save(buf)
from shutil import copyfileobj
copyfileobj(request.files['photo'].stream, buf, 16384)
```
Looks like we need to do some shuffling with the order we check the types and do the conversion, in order to continue to support file-like objects. Scheduled for 1.0.1, PRs welcome if anyone can work on a fix.

Resolving patch:
diff --git a/src/werkzeug/datastructures.py b/src/werkzeug/datastructures.py
--- a/src/werkzeug/datastructures.py
+++ b/src/werkzeug/datastructures.py
@@ -3058,7 +3058,9 @@ def save(self, dst, buffer_size=16384):
         from shutil import copyfileobj
 
         close_dst = False
-        dst = fspath(dst)
+
+        if hasattr(dst, "__fspath__"):
+            dst = fspath(dst)
 
         if isinstance(dst, string_types):
             dst = open(dst, "wb")


Test patch:
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py
--- a/tests/test_datastructures.py
+++ b/tests/test_datastructures.py
@@ -1243,6 +1243,20 @@ def test_save_to_pathlib_dst(self, tmp_path):
         storage.save(dst)
         assert dst.read_text() == "test"
 
+    def test_save_to_bytes_io(self):
+        storage = self.storage_class(io.BytesIO(b"one\ntwo"))
+        dst = io.BytesIO()
+        storage.save(dst)
+        assert dst.getvalue() == b"one\ntwo"
+
+    def test_save_to_file(self, tmp_path):
+        path = tmp_path / "file.data"
+        storage = self.storage_class(io.BytesIO(b"one\ntwo"))
+        with path.open("wb") as dst:
+            storage.save(dst)
+        with path.open("rb") as src:
+            assert src.read() == b"one\ntwo"
+
 
 @pytest.mark.parametrize("ranges", ([(0, 1), (-5, None)], [(5, None)]))
 def test_range_to_header(ranges):
Repository: pallets/werkzeug

Issue:
_dump_date year conversion doesn't zfill(4)
I have some dates that have a year before year 1000 and the _dump_date function doesn't represent them as zero filled to 4 so parsing the output with '%a, %d %b %Y %H:%M:%S %Z' throws an exception.

```
index b428ceeb..d233d0f2 100644
--- a/src/werkzeug/http.py
+++ b/src/werkzeug/http.py
@@ -882,7 +882,7 @@ def _dump_date(d, delim):
             "Dec",
         )[d.tm_mon - 1],
         delim,
-        str(d.tm_year),
+        str(d.tm_year).zfill(4),
         d.tm_hour,
         d.tm_min,
         d.tm_sec,
```


Discussion:
I'm not clear why dates prior to 1000 are relevant in an HTTP context. Can you explain why you need Werkzeug's `http_date` for this?
_dump_date is used as the default datetime and date encoding function in Flask's JSONEncoder class:

https://github.com/pallets/flask/blob/master/src/flask/json/__init__.py
Since you have specialized data, you should probably be using a better representation than HTTP dates anyway. I'd recommend overriding `app.json_encoder`, or using something like Marshmallow to serialize your data first. I guess I'm fine with a PR, it just doesn't seem very relevant to typical HTTP date use cases.
I did override it. I figured I'd mention it in case you wanted to apply the included patch - it mitigates this python issue https://bugs.python.org/issue13305 in this case.

Since the function is being used for common date encoding in Flask maybe they should rethink the http_date use in their default encoder...

Thanks for the response.

Resolving patch:
diff --git a/src/werkzeug/http.py b/src/werkzeug/http.py
--- a/src/werkzeug/http.py
+++ b/src/werkzeug/http.py
@@ -865,7 +865,7 @@ def _dump_date(d, delim):
         d = d.utctimetuple()
     elif isinstance(d, (integer_types, float)):
         d = gmtime(d)
-    return "%s, %02d%s%s%s%s %02d:%02d:%02d GMT" % (
+    return "%s, %02d%s%s%s%04d %02d:%02d:%02d GMT" % (
         ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[d.tm_wday],
         d.tm_mday,
         delim,
@@ -884,7 +884,7 @@ def _dump_date(d, delim):
             "Dec",
         )[d.tm_mon - 1],
         delim,
-        str(d.tm_year),
+        d.tm_year,
         d.tm_hour,
         d.tm_min,
         d.tm_sec,


Test patch:
diff --git a/tests/test_http.py b/tests/test_http.py
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -668,6 +668,18 @@ def test_content_range_parsing(self):
         assert rv.length == 100
         assert rv.units == "bytes"
 
+    @pytest.mark.parametrize(
+        ("args", "expected"),
+        (
+            ((1, 1, 1), "Mon, 01 Jan 0001 00:00:00 GMT"),
+            ((999, 1, 1), "Tue, 01 Jan 0999 00:00:00 GMT"),
+            ((1000, 1, 1), "Wed, 01 Jan 1000 00:00:00 GMT"),
+            ((2020, 1, 1), "Wed, 01 Jan 2020 00:00:00 GMT"),
+        ),
+    )
+    def test_http_date_lt_1000(self, args, expected):
+        assert http.http_date(datetime(*args)) == expected
+
 
 class TestRegression(object):
     def test_best_match_works(self):
Repository: pallets/werkzeug

Issue:
Local variables not available in debug console in version 1.0
Take this simple script:

```python
from werkzeug.wrappers import Request, Response

some_global_variable = True

@Request.application
def application(request):
    msg = 'Hello, World!'
    return Response(msg2)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, application,
               use_reloader=True, use_debugger=True, use_evalex=True)
```

As expected, the application crashes when it tries to create the response because `msg2` doesn't exist. With version 0.16.1 and Python 3.8, I can view the value of the `msg` variable in the debug console. But if I upgrade to version 1.0, `msg` is no longer defined. Global variables are available, however. Here's a screenshot:

![image](https://user-images.githubusercontent.com/4453816/76369784-57a50500-62fa-11ea-97cf-98a0a65a44a4.png)



Discussion:

Resolving patch:
diff --git a/src/werkzeug/debug/console.py b/src/werkzeug/debug/console.py
--- a/src/werkzeug/debug/console.py
+++ b/src/werkzeug/debug/console.py
@@ -148,8 +148,9 @@ def func(source, filename, symbol):
 
 class _InteractiveConsole(code.InteractiveInterpreter):
     def __init__(self, globals, locals):
-        locals = dict(globals)
-        locals.update(locals)
+        _locals = dict(globals)
+        _locals.update(locals)
+        locals = _locals
         locals["dump"] = dump
         locals["help"] = helper
         locals["__loader__"] = self.loader = _ConsoleLoader()


Test patch:
Repository: pallets/werkzeug

Issue:
deprecate utils.HTMLBuilder
There are dedicated template libraries like Jinja, or libraries that do this type of object-based markup generation (dominate, lxml, etree, etc.). Nothing in Werkzeug itself uses it.


Discussion:

Resolving patch:
diff --git a/src/werkzeug/utils.py b/src/werkzeug/utils.py
--- a/src/werkzeug/utils.py
+++ b/src/werkzeug/utils.py
@@ -157,6 +157,9 @@ class HTMLBuilder:
 
     >>> html.p(html("<foo>"))
     '<p>&lt;foo&gt;</p>'
+
+    .. deprecated:: 2.0
+        Will be removed in 2.1.
     """
 
     _entity_re = re.compile(r"&([^;]+);")
@@ -200,12 +203,27 @@ class HTMLBuilder:
     _c_like_cdata = {"script", "style"}
 
     def __init__(self, dialect):
+        warnings.warn(
+            "'utils.HTMLBuilder' is deprecated and will be removed in 2.1.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
         self._dialect = dialect
 
     def __call__(self, s):
+        warnings.warn(
+            "'utils.HTMLBuilder' is deprecated and will be removed in 2.1.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
         return escape(s)
 
     def __getattr__(self, tag):
+        warnings.warn(
+            "'utils.HTMLBuilder' is deprecated and will be removed in 2.1.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
         if tag[:2] == "__":
             raise AttributeError(tag)
 


Test patch:
diff --git a/tests/test_utils.py b/tests/test_utils.py
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -248,37 +248,6 @@ def test_find_modules():
     ]
 
 
-def test_html_builder():
-    html = utils.html
-    xhtml = utils.xhtml
-    assert html.p("Hello World") == "<p>Hello World</p>"
-    assert html.a("Test", href="#") == '<a href="#">Test</a>'
-    assert html.br() == "<br>"
-    assert xhtml.br() == "<br />"
-    assert html.img(src="foo") == '<img src="foo">'
-    assert xhtml.img(src="foo") == '<img src="foo" />'
-    assert html.html(
-        html.head(html.title("foo"), html.script(type="text/javascript"))
-    ) == (
-        '<html><head><title>foo</title><script type="text/javascript">'
-        "</script></head></html>"
-    )
-    assert html("<foo>") == "&lt;foo&gt;"
-    assert html.input(disabled=True) == "<input disabled>"
-    assert xhtml.input(disabled=True) == '<input disabled="disabled" />'
-    assert html.input(disabled="") == "<input>"
-    assert xhtml.input(disabled="") == "<input />"
-    assert html.input(disabled=None) == "<input>"
-    assert xhtml.input(disabled=None) == "<input />"
-    assert (
-        html.script('alert("Hello World");') == '<script>alert("Hello World");</script>'
-    )
-    assert (
-        xhtml.script('alert("Hello World");')
-        == '<script>/*<![CDATA[*/alert("Hello World");/*]]>*/</script>'
-    )
-
-
 def test_header_set_duplication_bug():
     headers = Headers([("Content-Type", "text/html"), ("Foo", "bar"), ("Blub", "blah")])
     headers["blub"] = "hehe"
Repository: pallets/werkzeug

Issue:
Replace optparse with argparse
optparse is deprecated since python 2.7


Discussion:

Resolving patch:
diff --git a/src/werkzeug/serving.py b/src/werkzeug/serving.py
--- a/src/werkzeug/serving.py
+++ b/src/werkzeug/serving.py
@@ -906,17 +906,19 @@ def run_with_reloader(*args, **kwargs):
 
 def main():
     """A simple command-line interface for :py:func:`run_simple`."""
-    import optparse
+    import argparse
     from .utils import import_string
 
-    parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
-    parser.add_option(
+    parser = argparse.ArgumentParser(
+        description="Usage: %prog [options] app_module:app_object"
+    )
+    parser.add_argument(
         "-b",
         "--bind",
         dest="address",
         help="The hostname:port the app should listen on.",
     )
-    parser.add_option(
+    parser.add_argument(
         "-d",
         "--debug",
         dest="use_debugger",
@@ -924,7 +926,7 @@ def main():
         default=False,
         help="Use Werkzeug's debugger.",
     )
-    parser.add_option(
+    parser.add_argument(
         "-r",
         "--reload",
         dest="use_reloader",


Test patch:
Repository: pallets/werkzeug

Issue:
Deprecate undocumented server CLI
I'm not sure anyone even knows about it. I was certainly surprised when I discovered it while doing some other work on that file. It doesn't appear to be documented in any version of the docs currently hosted.

_Originally posted by @davidism in https://github.com/pallets/werkzeug/issues/1827#issuecomment-641309197_


Discussion:

Resolving patch:
diff --git a/src/werkzeug/serving.py b/src/werkzeug/serving.py
--- a/src/werkzeug/serving.py
+++ b/src/werkzeug/serving.py
@@ -909,6 +909,8 @@ def main():
     import argparse
     from .utils import import_string
 
+    _log("warning", "This CLI is deprecated and will be removed in 3.1.")
+
     parser = argparse.ArgumentParser(
         description="Usage: %prog [options] app_module:app_object"
     )


Test patch:
Repository: pallets/werkzeug

Issue:
send_file should raise TypeError when mimetype and download_name aren't provided
All other places in `send_file` that check required parameter combinations raise a `TypeError`, but `mimetype` raises a `ValueError`.


Discussion:

Resolving patch:
diff --git a/src/werkzeug/utils.py b/src/werkzeug/utils.py
--- a/src/werkzeug/utils.py
+++ b/src/werkzeug/utils.py
@@ -643,7 +643,7 @@ def send_file(
 
     if mimetype is None:
         if download_name is None:
-            raise ValueError(
+            raise TypeError(
                 "Unable to detect the MIME type because a file name is"
                 " not available. Either set 'download_name', pass a"
                 " path instead of a file, or set 'mimetype'."


Test patch:
diff --git a/tests/test_send_file.py b/tests/test_send_file.py
--- a/tests/test_send_file.py
+++ b/tests/test_send_file.py
@@ -52,7 +52,7 @@ def test_object(file_factory):
 
 
 def test_object_without_mimetype():
-    with pytest.raises(ValueError, match="detect the MIME type"):
+    with pytest.raises(TypeError, match="detect the MIME type"):
         send_file(io.BytesIO(b"test"), environ)