internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: aio-libs/aiohttp

Issue:
Chat demo not working in aiohttp 3
## Long story short

Want to learn websockets with example code. There's a lack of simple and runnable example code on the net demonstrating websockets in python.

## Expected behaviour

Server runs and page loads

## Actual behaviour

Server runs but page fails to load with following error:
```
~/work/aiohttp/demos/chat$ ~/venv3/bin/python aiohttpdemo_chat/main.py 
DEBUG:asyncio:Using selector: EpollSelector
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
ERROR:aiohttp.server:Error handling request
Traceback (most recent call last):
  File "/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_protocol.py", line 381, in start
    resp = await self._request_handler(request)
  File "/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_app.py", line 310, in _handle
    resp = await handler(request)
  File "/home/robin/venv3/lib/python3.6/site-packages/aiohttpdemo_chat-0.0.1-py3.6.egg/aiohttpdemo_chat/views.py", line 15, in index
    ok, protocol = resp.can_start(request)
AttributeError: 'WebSocketResponse' object has no attribute 'can_start'
```

## Steps to reproduce

Just run `aiohttpdemo_chat/main.py`

## Your environment

archlinux, aiohttp 3.0.5 server?



Discussion:
The poll demo also does not work
This should probably be on https://github.com/aio-libs/aiohttp-demos.

The proper solution here is to add unit tests to that app and remember to run them (as we already do for other related projects) before major deploys.
https://github.com/aio-libs/aiohttp-demos gives the same error

Resolving patch:
diff --git a/demos/chat/aiohttpdemo_chat/views.py b/demos/chat/aiohttpdemo_chat/views.py
--- a/demos/chat/aiohttpdemo_chat/views.py
+++ b/demos/chat/aiohttpdemo_chat/views.py
@@ -12,8 +12,8 @@
 
 async def index(request):
     resp = web.WebSocketResponse()
-    ok, protocol = resp.can_start(request)
-    if not ok:
+    is_ws = resp.can_prepare(request)
+    if not is_ws:
         return aiohttp_jinja2.render_template('index.html', request, {})
 
     await resp.prepare(request)


Test patch:
diff --git a/tests/autobahn/server.py b/tests/autobahn/server.py
--- a/tests/autobahn/server.py
+++ b/tests/autobahn/server.py
@@ -8,8 +8,8 @@
 
 async def wshandler(request):
     ws = web.WebSocketResponse(autoclose=False)
-    ok, protocol = ws.can_start(request)
-    if not ok:
+    is_ws = ws.can_prepare(request)
+    if not is_ws:
         return web.HTTPBadRequest()
 
     await ws.prepare(request)
Repository: aio-libs/aiohttp

Issue:
'UrlDispatcher' object has no attribute 'add_options'
with

```py
web.route(METH_OPTIONS, '/foo/', foo, name='foo'),
```

https://github.com/aio-libs/aiohttp/blob/d8831f36d0ba1c7e2ffa7f5442e14d020de98bb8/aiohttp/web_routedef.py#L35-L41

`OPTIONS` is included in `METH_ALL`, however [`UrlDispatcher`](https://github.com/aio-libs/aiohttp/blob/master/aiohttp/web_urldispatcher.py#L785) has no `add_options` method.

I believe this is a bug.


Discussion:
Yes, indeed!
Would you fix it?

Resolving patch:
diff --git a/aiohttp/web_routedef.py b/aiohttp/web_routedef.py
--- a/aiohttp/web_routedef.py
+++ b/aiohttp/web_routedef.py
@@ -6,7 +6,7 @@
 from . import hdrs
 
 
-__all__ = ('RouteDef', 'StaticDef', 'RouteTableDef', 'head', 'get',
+__all__ = ('RouteDef', 'StaticDef', 'RouteTableDef', 'head', 'options', 'get',
            'post', 'patch', 'put', 'delete', 'route', 'view',
            'static')
 
@@ -67,6 +67,10 @@ def head(path, handler, **kwargs):
     return route(hdrs.METH_HEAD, path, handler, **kwargs)
 
 
+def options(path, handler, **kwargs):
+    return route(hdrs.METH_OPTIONS, path, handler, **kwargs)
+
+
 def get(path, handler, *, name=None, allow_head=True, **kwargs):
     return route(hdrs.METH_GET, path, handler, name=name,
                  allow_head=allow_head, **kwargs)
diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py
--- a/aiohttp/web_urldispatcher.py
+++ b/aiohttp/web_urldispatcher.py
@@ -906,6 +906,12 @@ def add_head(self, path, handler, **kwargs):
         """
         return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs)
 
+    def add_options(self, path, handler, **kwargs):
+        """
+        Shortcut for add_route with method OPTIONS
+        """
+        return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
+
     def add_get(self, path, handler, *, name=None, allow_head=True, **kwargs):
         """
         Shortcut for add_route with method GET, if allow_head is true another


Test patch:
diff --git a/tests/test_route_def.py b/tests/test_route_def.py
--- a/tests/test_route_def.py
+++ b/tests/test_route_def.py
@@ -42,6 +42,19 @@ async def handler(request):
     assert str(route.url_for()) == '/'
 
 
+def test_options(router):
+    async def handler(request):
+        pass
+
+    router.add_routes([web.options('/', handler)])
+    assert len(router.routes()) == 1
+
+    route = list(router.routes())[0]
+    assert route.handler is handler
+    assert route.method == 'OPTIONS'
+    assert str(route.url_for()) == '/'
+
+
 def test_post(router):
     async def handler(request):
         pass
Repository: aio-libs/aiohttp

Issue:
Change appveyor account
https://github.com/aio-libs/aiohttp/pull/2990#discussion_r187559585:

> This requires owner privileges AFAIR, so I can't. It's a bit tricky, but the bottom line is that you create a team there mapped to the team in GitHub and give it some access there. Also you need to somehow create an org link there.

> Here you go: https://www.appveyor.com/docs/team-setup/#setting-up-appveyor-account-for-github-organization
Create a separate account called aio-libs and then add your personal account as its administrator. You can also create team mapped to some team in GitHub, allowing its members to cancel/rerun builds.


Discussion:
* https://ci.appveyor.com/project/aio-libs/aiohttp
* https://ci.appveyor.com/project/aio-libs/aiohttp-devtools
* https://ci.appveyor.com/project/aio-libs/multidict

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -119,7 +119,7 @@ def read(f):
     url='https://github.com/aio-libs/aiohttp',
     project_urls={
         'Chat: Gitter': 'https://gitter.im/aio-libs/Lobby',
-        'CI: AppVeyor': 'https://ci.appveyor.com/project/asvetlov/aiohttp',  # FIXME: move under aio-libs/* slug
+        'CI: AppVeyor': 'https://ci.appveyor.com/project/aio-libs/aiohttp',
         'CI: Circle': 'https://circleci.com/gh/aio-libs/aiohttp',
         'CI: Shippable': 'https://app.shippable.com/github/aio-libs/aiohttp',
         'CI: Travis': 'https://travis-ci.com/aio-libs/aiohttp',


Test patch:
Repository: aio-libs/aiohttp

Issue:
Remove reader parameter from request.multipart()
The parameter exists from the very beginning, it is declared as:
```
    async def multipart(self, *, reader=multipart.MultipartReader):
```
I found that we can drop it: `reader` is always `multipart.MultipartReader`, aiohttp doesn't provide an alternative multipart reader implementation.

I have a problem with adding type hints to the method. Now it can return anything which is returned by `reader(headers, content)` call.  Dropping the parameter allows specifying the method return type without any functionality lose.

@kxepal maybe you have a comment?


Discussion:
IIRC it was made exactly for alternative implementations which the end user may have (something special, patched or fixed, but he's unable to upgrade aiohttp) and tests when you may be need eventually some mocked MultipartReader. 

Personally, I'm not user of this one, but may be someone found it useful. If nobody argue - let's do that. Not all features are useful as their authors were thought.
User always can call `AlternativeReader(req.headers, req.content)`
Than problem is solved (: 

Resolving patch:
diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py
--- a/aiohttp/web_request.py
+++ b/aiohttp/web_request.py
@@ -19,8 +19,9 @@
 from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
 from yarl import URL
 
-from . import hdrs, multipart
+from . import hdrs
 from .helpers import DEBUG, ChainMapProxy, HeadersMixin, reify, sentinel
+from .multipart import MultipartReader
 from .streams import EmptyStreamReader, StreamReader
 from .typedefs import JSONDecoder, LooseHeaders, RawHeaders, StrOrURL
 from .web_exceptions import HTTPRequestEntityTooLarge
@@ -548,9 +549,9 @@ async def json(self, *, loads: JSONDecoder=DEFAULT_JSON_DECODER) -> Any:
         body = await self.text()
         return loads(body)
 
-    async def multipart(self, *, reader=multipart.MultipartReader):
+    async def multipart(self) -> MultipartReader:
         """Return async iterator to process BODY as multipart."""
-        return reader(self._headers, self._payload)
+        return MultipartReader(self._headers, self._payload)
 
     async def post(self) -> MultiDictProxy:
         """Return POST parameters."""


Test patch:
Repository: aio-libs/aiohttp

Issue:
multipart BodyPartReaderPayload filename wrong
https://github.com/aio-libs/aiohttp/blob/d8831f36d0ba1c7e2ffa7f5442e14d020de98bb8/aiohttp/multipart.py#L446-L448

Maybe I'm missing something, but this looks wrong, shouldn't it be `value.filename`?


Discussion:
I don't know.
@kxepal could you take a look?
I'm pretty busy now. Will have a time next week. 
happy to correct and write unit tests, but I need to check I'm not missing something before I go any further.
For me it looks like a typo which should be fixed.
Yeah. Definitely a copy-paste typo.
ok, I'm manic this week, but will try to provide a fix next week. I noticed it because this function doesn't have very good coverage, so will try to improve that too.
Cool!

Resolving patch:
diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py
--- a/aiohttp/multipart.py
+++ b/aiohttp/multipart.py
@@ -444,7 +444,7 @@ def __init__(self, value, *args, **kwargs):
         if value.name is not None:
             params['name'] = value.name
         if value.filename is not None:
-            params['filename'] = value.name
+            params['filename'] = value.filename
 
         if params:
             self.set_content_disposition('attachment', **params)


Test patch:
diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py
--- a/tests/test_web_functional.py
+++ b/tests/test_web_functional.py
@@ -1566,6 +1566,56 @@ async def handler(request):
                     {'name': 'file', 'filename': 'file', 'filename*': 'file'})
 
 
+async def test_response_with_bodypart_named(aiohttp_client, tmpdir):
+
+    async def handler(request):
+        reader = await request.multipart()
+        part = await reader.next()
+        return web.Response(body=part)
+
+    app = web.Application(client_max_size=2)
+    app.router.add_post('/', handler)
+    client = await aiohttp_client(app)
+
+    f = tmpdir.join('foobar.txt')
+    f.write_text('test', encoding='utf8')
+    data = {'file': open(str(f), 'rb')}
+    resp = await client.post('/', data=data)
+
+    assert 200 == resp.status
+    body = await resp.read()
+    assert body == b'test'
+
+    disp = multipart.parse_content_disposition(
+        resp.headers['content-disposition'])
+    assert disp == (
+        'attachment',
+        {'name': 'file', 'filename': 'foobar.txt', 'filename*': 'foobar.txt'}
+    )
+
+
+async def test_response_with_bodypart_invalid_name(aiohttp_client):
+
+    async def handler(request):
+        reader = await request.multipart()
+        part = await reader.next()
+        return web.Response(body=part)
+
+    app = web.Application(client_max_size=2)
+    app.router.add_post('/', handler)
+    client = await aiohttp_client(app)
+
+    with aiohttp.MultipartWriter() as mpwriter:
+        mpwriter.append(b'test')
+        resp = await client.post('/', data=mpwriter)
+
+    assert 200 == resp.status
+    body = await resp.read()
+    assert body == b'test'
+
+    assert 'content-disposition' not in resp.headers
+
+
 async def test_request_clone(aiohttp_client):
 
     async def handler(request):
Repository: aio-libs/aiohttp

Issue:
HTTPException should retain cause information
## Long story short

I would like to use a pattern like:
```python
try:
    do_something()
except SomeException as e:
    raise HTTPInternalServerError(reason='My message') from e
```
with cause information retained. Does it make sense to implement `HTTPException.__bool__()` to always `True`?

## Expected behaviour

Two tracebacks separated by `The above exception was the direct cause of the following exception:`

## Actual behaviour

The cause information is lost, because `traceback.TracebackException` evaluates the [truthiness of the exception value](https://github.com/python/cpython/blob/de86073a761cd3539aaca6f886a1f55effc0d9da/Lib/traceback.py#L464) to determine whether cause lines are produced. For `HTTPException`, [truthiness is resolved](https://github.com/aio-libs/aiohttp/blob/7cf5785f5383ee67756d0f8d86ea3516b823b940/aiohttp/web_response.py#L426) via `StreamResponse.__len__()` which returns 0.

## Steps to reproduce

<!-- Please describe steps to reproduce the issue.
     If you have a script that does that please include it here within
     markdown code markup -->

## Your environment

<!-- Describe the environment you have that lead to your issue.
     This includes aiohttp version, OS, proxy server and other bits that
     are related to your case. 
     
     IMPORTANT: aiohttp is both server framework and client library.
     For getting rid of confusing please put 'server', 'client' or 'both'
     word here.
     -->



Discussion:
Yes, looks like `__bool__` is the best we can do in the situation.
Would you make a Pull Request?

Resolving patch:
diff --git a/aiohttp/web_exceptions.py b/aiohttp/web_exceptions.py
--- a/aiohttp/web_exceptions.py
+++ b/aiohttp/web_exceptions.py
@@ -83,6 +83,9 @@ def __init__(self, *, headers=None, reason=None,
         if self.body is None and not self.empty_body:
             self.text = "{}: {}".format(self.status, self.reason)
 
+    def __bool__(self):
+        return True
+
 
 class HTTPError(HTTPException):
     """Base class for exceptions with status codes in the 400s and 500s."""


Test patch:
diff --git a/tests/test_web_exceptions.py b/tests/test_web_exceptions.py
--- a/tests/test_web_exceptions.py
+++ b/tests/test_web_exceptions.py
@@ -1,5 +1,6 @@
 import collections
 import re
+from traceback import format_exception
 from unittest import mock
 
 import pytest
@@ -172,3 +173,14 @@ def test_link_header_451(buf, request):
 
     assert 'http://warning.or.kr/' == resp.link
     assert '<http://warning.or.kr/>; rel="blocked-by"' == resp.headers['Link']
+
+
+def test_HTTPException_retains_cause():
+    with pytest.raises(web.HTTPException) as ei:
+        try:
+            raise Exception('CustomException')
+        except Exception as exc:
+            raise web.HTTPException() from exc
+    tb = ''.join(format_exception(ei.type, ei.value, ei.tb))
+    assert 'CustomException' in tb
+    assert 'direct cause' in tb
Repository: aio-libs/aiohttp

Issue:
StreamResponse instances are all equal
## Long story short

Since #2494 , `StreamResponse` inherits `collections.MutableMapping.__eq__`, which makes them basically all equal. 
The implementation in `Mapping` looks like `return dict(self.items()) == dict(other.items())`.

This is especially the case for `WebSocketResponse` : when following https://aiohttp.readthedocs.io/en/stable/faq.html#how-do-i-programmatically-close-a-websocket-server-side, if you use a `list` instead of a `set`, it's impossible to `remove` the correct websocket.

## Expected behaviour

```python
>>> from aiohttp.web_ws import WebSocketResponse
>>> r1 = WebSocketResponse()
>>> r2 = WebSocketResponse()
>>> r1 == r2
False
>>> id(r1) == id(r2)
False
>>> r1 is r2
False
>>> hash(r1) == hash(r2)
False
```

As a rule, `a == b` implies `hash(a) == hash(b)`. But it's now broken.

## Actual behaviour

Since v3.0:
```python
>>> r1 == r2
True
>>> id(r1) == id(r2)
False
>>> r1 is r2
False
>>> hash(r1) == hash(r2)
False
```

## Steps to reproduce

Described above

## Your environment

* `aiohttp >= 3.0`



Discussion:
You are right.
```
def __eq__(self, other):
    return False
```
could solve the problem, at least I don't see any drawback.
Would you make a Pull Request with the fix?

Resolving patch:
diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py
--- a/aiohttp/web_response.py
+++ b/aiohttp/web_response.py
@@ -432,6 +432,9 @@ def __iter__(self):
     def __hash__(self):
         return hash(id(self))
 
+    def __eq__(self, other):
+        return self is other
+
 
 class Response(StreamResponse):
 


Test patch:
diff --git a/tests/test_web_response.py b/tests/test_web_response.py
--- a/tests/test_web_response.py
+++ b/tests/test_web_response.py
@@ -82,6 +82,14 @@ def test_stream_response_hashable():
     hash(StreamResponse())
 
 
+def test_stream_response_eq():
+    resp1 = StreamResponse()
+    resp2 = StreamResponse()
+
+    assert resp1 == resp1
+    assert not resp1 == resp2
+
+
 def test_stream_response_is_mutable_mapping():
     resp = StreamResponse()
     assert isinstance(resp, collections.MutableMapping)
Repository: aio-libs/aiohttp

Issue:
Every request object is equal
It seems the `==` operator evals to `True` for every request object.

```python
from aiohttp.test_utils import make_mocked_request

def test_path_equals():
    req = make_mocked_request('GET', '/a/')
    req2 = make_mocked_request('GET', '/b/')
    assert req.path != req2.path
    assert req != req2

def test_method_equals():
    req = make_mocked_request('GET', '/a/')
    req2 = make_mocked_request('POST', '/a/')
    assert req.method != req2.method
    assert req != req2
    
def test_equals():
    req = make_mocked_request('GET', '/this/isnot/evenclose')
    req2 = make_mocked_request('OPTIONS', '/search?query=what')
    assert req.path != req2.path
    assert req.method != req2.method
    assert req != req2
```

Is this intentional?


Discussion:
The problem is exactly the same as #3107 for response
Comparison and hashing should be disabled for request objects.
I very curious what is your use case for requests comparison.
The [template engine](https://github.com/codelv/enaml-web) I use builds a dom and automatically updates necessary parts of the page (form fields or user specific content) when the request changes.  

Since all the requests were equal, it wasn't updating automatically.  I just patched requests to use the id for comparison.

```python
from aiohttp.web_request import BaseRequest

#: Equals returns true even though the requests are completely different
BaseRequest.__eq__ = lambda self, other: id(self) == id(other)

```

Resolving patch:
diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py
--- a/aiohttp/web_request.py
+++ b/aiohttp/web_request.py
@@ -634,6 +634,9 @@ def __repr__(self):
         return "<{} {} {} >".format(self.__class__.__name__,
                                     self._method, ascii_encodable_path)
 
+    def __eq__(self, other):
+        return id(self) == id(other)
+
     @asyncio.coroutine
     def _prepare_hook(self, response):
         return


Test patch:
diff --git a/tests/test_web_request.py b/tests/test_web_request.py
--- a/tests/test_web_request.py
+++ b/tests/test_web_request.py
@@ -634,3 +634,10 @@ def test_remote_with_closed_transport():
     req = make_mocked_request('GET', '/')
     req._protocol = None
     assert req.remote is None
+
+
+def test_eq():
+    req1 = make_mocked_request('GET', '/path/to?a=1&b=2')
+    req2 = make_mocked_request('GET', '/path/to?a=1&b=2')
+    assert req1 != req2
+    assert req1 == req1
Repository: aio-libs/aiohttp

Issue:
Drop loop.current_task() in helpers.current_task()
When tokio will be ready (see PyO3/tokio#106)


Discussion:

Resolving patch:
diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py
--- a/aiohttp/helpers.py
+++ b/aiohttp/helpers.py
@@ -195,19 +195,10 @@ def proxies_from_env():
 
 
 def current_task(loop=None):
-    if loop is None:
-        loop = asyncio.get_event_loop()
-
     if PY_37:
-        task = asyncio.current_task(loop=loop)
+        return asyncio.current_task(loop=loop)
     else:
-        task = asyncio.Task.current_task(loop=loop)
-    if task is None:
-        # this should be removed, tokio must use register_task and family API
-        if hasattr(loop, 'current_task'):
-            task = loop.current_task()
-
-    return task
+        return asyncio.Task.current_task(loop=loop)
 
 
 def isasyncgenfunction(obj):


Test patch:
Repository: aio-libs/aiohttp

Issue:
Windows documentation build failure
### Long story short

Building the documentation fails on Windows

### Expected behaviour

Successful documentation build

### Actual behaviour

Attempts error with:
```
Configuration error:
There is a programable error in your configuration file:

Traceback (most recent call last):
  File "c:\program files\python36\lib\site-packages\sphinx\config.py", line 161, in __init__
    execfile_(filename, config)
  File "c:\program files\python36\lib\site-packages\sphinx\util\pycompat.py", line 150, in execfile_
    exec_(code, _globals)
  File "conf.py", line 31, in <module>
    fp.read(), re.M).groupdict()
AttributeError: 'NoneType' object has no attribute 'groupdict'
```
This is caused by usage of `codecs.open`, for which "[no automatic conversion of '\n' is done on reading and writing.](https://docs.python.org/3/library/codecs.html#codecs.open)" Therefore, "\r\n" is not converted to '\n', and the regex search fails with the carriage return and returns `None`.

### Steps to reproduce

`make doc`
per https://docs.aiohttp.org/en/stable/contributing.html#documentation

### Environment

Windows
Recommended Git line ending setting for Windows of "Checkout Windows-style, commit Unix-style", i.e. core.autocrlf set to true
Latest aiohttp cloned from repository



Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -13,7 +13,7 @@
 # All configuration values have a default; values that are commented out
 # serve to show the default.
 
-import codecs
+import io
 import os
 import re
 import sys
@@ -21,7 +21,7 @@
 _docs_path = os.path.dirname(__file__)
 _version_path = os.path.abspath(os.path.join(_docs_path,
                                              '..', 'aiohttp', '__init__.py'))
-with codecs.open(_version_path, 'r', 'latin1') as fp:
+with io.open(_version_path, 'r', encoding='latin1') as fp:
     try:
         _version_info = re.search(r"^__version__ = '"
                                   r"(?P<major>\d+)"


Test patch: