1
1
import asyncio
2
2
import json
3
- from urllib .parse import urlparse , parse_qsl
4
-
5
- from aiohttp .server import ServerHttpProtocol
6
- from aiohttp import Response
7
3
8
4
from pytest import yield_fixture , fixture
9
5
6
+ import aiohttp .web
10
7
from elasticsearch_async import AIOHttpConnection , AsyncElasticsearch
11
8
12
9
13
10
@yield_fixture
14
11
def connection (event_loop , server , port ):
15
12
connection = AIOHttpConnection (port = port , loop = event_loop )
16
13
yield connection
17
- event_loop .run_until_complete (connection .close ())
14
+ connection .close ()
15
+
16
+
17
+ class DummyElasticsearch (aiohttp .web .Server ):
18
18
19
- class DummyElasticsearch (ServerHttpProtocol ):
20
19
def __init__ (self , ** kwargs ):
21
- super ().__init__ (** kwargs )
20
+ super ().__init__ (handler = self . handler , ** kwargs )
22
21
self ._responses = {}
23
22
self .calls = []
24
23
25
24
def register_response (self , path , response = {}, status = 200 ):
26
25
self ._responses [path ] = status , response
27
26
28
27
@asyncio .coroutine
29
- def handle_request (self , message , payload ):
30
- url = urlparse ( message . path )
28
+ def handler (self , request ):
29
+ url = request . url
31
30
32
- params = dict (parse_qsl ( url .query ) )
33
- body = yield from payload .read ()
31
+ params = dict (request .query )
32
+ body = yield from request .read ()
34
33
body = json .loads (body .decode ('utf-8' )) if body else ''
35
34
36
- self .calls .append ((message .method , url .path , body , params ))
35
+ self .calls .append ((request .method , url .path , body , params ))
37
36
38
37
if url .path in self ._responses :
39
38
status , body = self ._responses .pop (url .path )
@@ -42,18 +41,16 @@ def handle_request(self, message, payload):
42
41
else :
43
42
status = 200
44
43
body = {
45
- 'method' : message .method ,
44
+ 'method' : request .method ,
46
45
'params' : params ,
47
46
'path' : url .path ,
48
47
'body' : body
49
48
}
50
49
51
- out = json .dumps (body ).encode ('utf-8' )
50
+ out = json .dumps (body )
51
+
52
+ return aiohttp .web .Response (body = out , status = status , content_type = 'application/json' )
52
53
53
- response = Response (self .writer , status )
54
- response .send_headers ()
55
- response .write (out )
56
- yield from response .write_eof ()
57
54
58
55
i = 0
59
56
@fixture
@@ -62,12 +59,13 @@ def port():
62
59
i += 1
63
60
return 8080 + i
64
61
65
- @fixture
62
+ @yield_fixture
66
63
def server (event_loop , port ):
67
64
server = DummyElasticsearch (debug = True , keep_alive = 75 )
68
- f = event_loop .create_server (lambda : server , '127.0.0.1' , port )
65
+ f = event_loop .create_server (server , '127.0.0.1' , port )
69
66
event_loop .run_until_complete (f )
70
- return server
67
+ yield server
68
+ event_loop .run_until_complete (server .shutdown (timeout = .5 ))
71
69
72
70
@yield_fixture
73
71
def client (event_loop , server , port ):
0 commit comments