anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: sanic-org/sanic
Issue: Disabling debug mode?

I can't seem to disable the debug mode, is this normal?

```python
from rise.server.wsgi import app, config

# config['debug'] = False
app.run(**config)
```

```bash
{'port': 5000, 'debug': False, 'host': '0.0.0.0'}
2017-08-22 23:59:32 - (sanic)[DEBUG]:
                 ▄▄▄▄▄
        ▀▀▀██████▄▄▄       _______________
      ▄▄▄▄▄  █████████▄  /                 \\
     ▀▀▀▀█████▌ ▀▐▄ ▀▐█ |   Gotta go fast!  |
   ▀▀█████▄▄ ▀██████▄██ | _________________/
   ▀▄▄▄▄▄  ▀▀█▄▀█════█▀ |/
        ▀▀▀▄  ▀▀███ ▀       ▄▄
     ▄███▀▀██▄████████▄ ▄▀▀▀▀▀▀█▌
   ██▀▄▄▄██▀▄███▀ ▀▀████      ▄██
▄▀▀▀▄██▄▀▀▌████▒▒▒▒▒▒███     ▌▄▄▀
▌    ▐▀████▐███▒▒▒▒▒▐██▌
▀▄▄▄▄▀   ▀▀████▒▒▒▒▄██▀
          ▀▀█████████▀
        ▄▄██▀██████▀█
      ▄██▀     ▀▀▀  █
     ▄█             ▐▌
 ▄▄▄▄█▌              ▀█▄▄▄▄▀▀▄
▌     ▐                ▀▀▄▄▄▀
 ▀▀▄▄▀

DEBUG:sanic:
                 ▄▄▄▄▄
        ▀▀▀██████▄▄▄       _______________
      ▄▄▄▄▄  █████████▄  /                 \\
     ▀▀▀▀█████▌ ▀▐▄ ▀▐█ |   Gotta go fast!  |
   ▀▀█████▄▄ ▀██████▄██ | _________________/
   ▀▄▄▄▄▄  ▀▀█▄▀█════█▀ |/
        ▀▀▀▄  ▀▀███ ▀       ▄▄
     ▄███▀▀██▄████████▄ ▄▀▀▀▀▀▀█▌
   ██▀▄▄▄██▀▄███▀ ▀▀████      ▄██
▄▀▀▀▄██▄▀▀▌████▒▒▒▒▒▒███     ▌▄▄▀
▌    ▐▀████▐███▒▒▒▒▒▐██▌
▀▄▄▄▄▀   ▀▀████▒▒▒▒▄██▀
          ▀▀█████████▀
        ▄▄██▀██████▀█
      ▄██▀     ▀▀▀  █
     ▄█             ▐▌
 ▄▄▄▄█▌              ▀█▄▄▄▄▀▀▄
▌     ▐                ▀▀▄▄▄▀
 ▀▀▄▄▀

2017-08-22 23:59:32 - (sanic)[INFO]: Goin' Fast @ http://0.0.0.0:5000
INFO:sanic:Goin' Fast @ http://0.0.0.0:5000
2017-08-22 23:59:32 - (sanic)[INFO]: Starting worker [39513]
INFO:sanic:Starting worker [39513]
```

Changed files:
sanic/config.py

diff --git a/sanic/config.py b/sanic/config.py
index e8846465..0c2cc701 100644
--- a/sanic/config.py
+++ b/sanic/config.py
@@ -81,11 +81,11 @@ LOGGING = {
     },
     'loggers': {
         'sanic': {
-            'level': 'DEBUG',
+            'level': 'INFO',
             'handlers': ['internal', 'errorStream']
         },
         'network': {
-            'level': 'DEBUG',
+            'level': 'INFO',
             'handlers': ['accessStream', 'errorStream']
         }
     }
Repository: sanic-org/sanic
Issue: Bad char cause parse exception  and how to log the url when request can't be parsed?

Using: sanic 0.5.1  (While I don't see which change with 0.5.4 in changelog)

In our code we using : 

```
@app.exception(Exception)
def server_error_handler(request, exception):
    if request is not None:
        msg = request.url + ' ' + traceback.format_exc()
    elif isinstance(exception, RequestTimeout):
        return response.text('timeout', status=504)
    else:
        msg = str(exception) + ' ' + traceback.format_exc()
    asyncio.ensure_future(fluent.write_debug('error', msg))
``` 
to log exception.  We find error has : 

 
> Bad Request Traceback (most recent call last):
>   File "httptools/parser/parser.pyx", line 247, in httptools.parser.parser.cb_on_header_field (httptools/parser/parser.c:4007)
>   File "httptools/parser/parser.pyx", line 109, in httptools.parser.parser.HttpParser._on_header_field (httptools/parser/parser.c:1893)
>   File "httptools/parser/parser.pyx", line 105, in httptools.parser.parser.HttpParser._maybe_call_on_header (httptools/parser/parser.c:1822)
>   File "/usr/local/lib/python3.5/dist-packages/sanic/server.py", line 157, in on_header
>     self.headers.append((name.decode().casefold(), value.decode()))
> AttributeError: 'NoneType' object has no attribute 'decode'
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
>   File "/usr/local/lib/python3.5/dist-packages/sanic/server.py", line 144, in data_received
>     self.parser.feed_data(data)
>   File "httptools/parser/parser.pyx", line 171, in httptools.parser.parser.HttpParser.feed_data (httptools/parser/parser.c:2721)
> httptools.parser.errors.HttpParserCallbackError: the on_header_field callback failed

At this moment the request have not been created. So is there a method can I log the access url ?




Changed files:
sanic/server.py

diff --git a/sanic/server.py b/sanic/server.py
index f62ba654..4dedc650 100644
--- a/sanic/server.py
+++ b/sanic/server.py
@@ -189,10 +189,12 @@ class HttpProtocol(asyncio.Protocol):
                     and int(value) > self.request_max_size:
                 exception = PayloadTooLarge('Payload Too Large')
                 self.write_error(exception)
-
+            try:
+                value = value.decode()
+            except UnicodeDecodeError:
+                value = value.decode('latin_1')
             self.headers.append(
-                    (self._header_fragment.decode().casefold(),
-                     value.decode()))
+                    (self._header_fragment.decode().casefold(), value))
 
             self._header_fragment = b''
Repository: sanic-org/sanic
Issue: [Errno 13] Permission denied: '/access.log' with disabled debug & logging?

With:

```text
app.run(host=API_HOST, port=PORT, sock=None, debug=False, workers=API_WORKERS, log_config=None)
```

```text
app = Sanic(__name__)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/site-packages/sanic/app.py", line 33, in __init__
    logging.config.dictConfig(log_config)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'accessTimedRotatingFile': [Errno 13] Permission denied: '/access.log'
```

Changed files:
sanic/app.py

diff --git a/sanic/app.py b/sanic/app.py
index f6b1e84e..01af3526 100644
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -33,7 +33,9 @@ class Sanic:
             logging.config.dictConfig(log_config)
         # Only set up a default log handler if the
         # end-user application didn't set anything up.
-        if not logging.root.handlers and log.level == logging.NOTSET:
+        if not (logging.root.handlers and
+                log.level == logging.NOTSET and
+                log_config):
             formatter = logging.Formatter(
                 "%(asctime)s: %(levelname)s: %(message)s")
             handler = logging.StreamHandler()
Repository: sanic-org/sanic
Issue: Streaming Response Chunked Encoding Incomplete Read Error

The new `stream` method works with the [demo example](http://sanic.readthedocs.io/en/latest/sanic/streaming.html), but if I try to stream larger chunks of data (e.g. 10 bytes) I get a ChunkedEncodingError / broken connection / Incomplete Read on the client.

I confirmed this on both latest master 62ebcba64 and when the feature was introduced at 19592e8eea.

Here is a slightly modified test demo server to reproduce the problem:
```
from sanic import Sanic
from sanic.response import stream

app = Sanic(__name__)

@app.route("/")
async def test(request):
    async def sample_streaming_fn(response):
        response.write('foo,bat,baz,')
        response.write('bar')

    return stream(sample_streaming_fn, content_type='text/csv')

app.run(host="0.0.0.0", port=8000, workers=1)
```

Start this test server with:
```
$ docker run --rm -it -v `pwd`:/app -p 8000:8000 ubergarm/sanic-alpine /app/test.py
2017-04-04 17:27:49,501: INFO: Goin' Fast @ http://0.0.0.0:8000
2017-04-04 17:27:49,503: INFO: Starting worker [1]
```

Test with `curl`:
```
$ curl -v localhost:8000
* Rebuilt URL to: localhost:8000/
*   Trying ::1...
* Connected to localhost (::1) port 8000 (#0)
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Keep-Alive: 60
< Transfer-Encoding: chunked
< Content-Type: text/csv
<
foo,bat,baz,
3
* Malformed encoding found in chunked-encoding
* Closing connection 0
curl: (56) Malformed encoding found in chunked-encoding
```

Test with `httpie`:
```
$ http -v localhost:8000
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8000
User-Agent: HTTPie/0.9.4



HTTP/1.1 200 OK
Content-Type: text/csv
Keep-Alive: 60
Transfer-Encoding: chunked


http: error: ChunkedEncodingError: ('Connection broken: IncompleteRead(2 bytes read)', IncompleteRead(2 bytes read))
```

Changed files:
sanic/response.py

diff --git a/sanic/response.py b/sanic/response.py
index 4eecaf79..bebb8071 100644
--- a/sanic/response.py
+++ b/sanic/response.py
@@ -129,7 +129,7 @@ class StreamingHTTPResponse(BaseHTTPResponse):
             data = self._encode_body(data)
 
         self.transport.write(
-            b"%b\\r\\n%b\\r\\n" % (str(len(data)).encode(), data))
+            b"%x\\r\\n%b\\r\\n" % (len(data), data))
 
     async def stream(
             self, version="1.1", keep_alive=False, keep_alive_timeout=None):
Repository: sanic-org/sanic
Issue: [Errno 13] Permission denied: '/access.log' with disabled debug & logging?

With:

```text
app.run(host=API_HOST, port=PORT, sock=None, debug=False, workers=API_WORKERS, log_config=None)
```

```text
app = Sanic(__name__)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/site-packages/sanic/app.py", line 33, in __init__
    logging.config.dictConfig(log_config)
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/local/anaconda/envs/proj/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'accessTimedRotatingFile': [Errno 13] Permission denied: '/access.log'
```

Changed files:
sanic/app.py, tests/test_logging.py

diff --git a/sanic/app.py b/sanic/app.py
index f1e8be7e..f0ccad86 100644
--- a/sanic/app.py
+++ b/sanic/app.py
@@ -33,9 +33,7 @@ class Sanic:
             logging.config.dictConfig(log_config)
         # Only set up a default log handler if the
         # end-user application didn't set anything up.
-        if not (logging.root.handlers and
-                log.level == logging.NOTSET and
-                log_config):
+        if not logging.root.handlers and log.level == logging.NOTSET:
             formatter = logging.Formatter(
                 "%(asctime)s: %(levelname)s: %(message)s")
             handler = logging.StreamHandler()
diff --git a/tests/test_logging.py b/tests/test_logging.py
index fc26ca93..d6911d86 100644
--- a/tests/test_logging.py
+++ b/tests/test_logging.py
@@ -1,5 +1,7 @@
-import asyncio
 import uuid
+from importlib import reload
+
+from sanic.config import LOGGING
 from sanic.response import text
 from sanic import Sanic
 from io import StringIO
@@ -10,6 +12,11 @@ function: %(funcName)s(); \\
 message: %(message)s'''
 
 
+def reset_logging():
+    logging.shutdown()
+    reload(logging)
+
+
 def test_log():
     log_stream = StringIO()
     for handler in logging.root.handlers[:]:
@@ -32,5 +39,19 @@ def test_log():
     log_text = log_stream.getvalue()
     assert rand_string in log_text
 
+
+def test_default_log_fmt():
+
+    reset_logging()
+    Sanic()
+    for fmt in [h.formatter for h in logging.getLogger('sanic').handlers]:
+        assert fmt._fmt == LOGGING['formatters']['simple']['format']
+
+    reset_logging()
+    Sanic(log_config=None)
+    for fmt in [h.formatter for h in logging.getLogger('sanic').handlers]:
+        assert fmt._fmt == "%(asctime)s: %(levelname)s: %(message)s"
+
+
 if __name__ == "__main__":
     test_log()
Repository: sanic-org/sanic
Issue: Add '%' to quote_plus's `safe` parameter in response.redirect

https://github.com/huge-success/sanic/blob/30e6a310f132752669a74927530e8bc52a51e98e/sanic/response.py#L367

```
from urllib.parse import urlencode
args = urlencode({"redirect_uri": "http://example.com"})
response.redirect(...args...)
>>> 'redirect_uri=http%253A%252F%252Fexample.com'
```
In this case it will be `quote_plus` twice, and generate extra '%25'。

Changed files:
tests/test_redirect.py, sanic/response.py

diff --git a/sanic/response.py b/sanic/response.py
index cf9aaba2..c32ed9ce 100644
--- a/sanic/response.py
+++ b/sanic/response.py
@@ -421,7 +421,7 @@ def redirect(
     headers = headers or {}
 
     # URL Quote the URL before redirecting
-    safe_to = quote_plus(to, safe=":/#?&=@[]!$&'()*+,;")
+    safe_to = quote_plus(to, safe=":/%#?&=@[]!$&'()*+,;")
 
     # According to RFC 7231, a relative URI is now permitted.
     headers["Location"] = safe_to
diff --git a/tests/test_redirect.py b/tests/test_redirect.py
index f5efac60..a6ccf5de 100644
--- a/tests/test_redirect.py
+++ b/tests/test_redirect.py
@@ -1,4 +1,5 @@
 import pytest
+from urllib.parse import quote
 
 from sanic.response import text, redirect
 
@@ -107,3 +108,25 @@ def test_redirect_with_header_injection(redirect_app):
     assert response.status == 302
     assert "test-header" not in response.headers
     assert not response.text.startswith('test-body')
+
+
+@pytest.mark.parametrize("test_str", ["sanic-test", "sanictest", "sanic test"])
+async def test_redirect_with_params(app, test_client, test_str):
+
+    @app.route("/api/v1/test/<test>/")
+    async def init_handler(request, test):
+        assert test == test_str
+        return redirect("/api/v2/test/{}/".format(quote(test)))
+
+    @app.route("/api/v2/test/<test>/")
+    async def target_handler(request, test):
+        assert test == test_str
+        return text("OK")
+
+    test_cli = await test_client(app)
+
+    response = await test_cli.get("/api/v1/test/{}/".format(quote(test_str)))
+    assert response.status == 200
+
+    txt = await response.text()
+    assert txt == "OK"