test_connection   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 25
eloc 93
dl 0
loc 129
rs 10
c 0
b 0
f 0

9 Functions

Rating   Name   Duplication   Size   Complexity  
A test_204_empty_stream() 0 11 3
A test_connection_response_timeout() 0 11 4
A test_get_close_conn() 0 8 1
A test_cant_connect() 0 4 2
A test_conn_context_manager() 0 5 2
A test_submit() 0 12 3
A test_resp_queue_removed_from_conn() 0 11 3
A test_stream_done() 0 10 3
A test_server_error() 0 10 4
1
# Copyright 2016 David M. Brown
2
#
3
# This file is part of Goblin.
4
#
5
# Goblin is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Affero General Public License as published by
7
# the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# Goblin is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Affero General Public License for more details.
14
#
15
# You should have received a copy of the GNU Affero General Public License
16
# along with Goblin.  If not, see <http://www.gnu.org/licenses/>.
17
import asyncio
18
import json
19
20
import base64
21
import pytest
22
23
import aiohttp
24
from aiohttp import web
25
26
from aiogremlin import driver
27
from aiogremlin import exception
28
from aiogremlin.driver import provider
29
from gremlin_python.driver import request, serializer
30
31
32
@pytest.mark.asyncio
33
async def test_get_close_conn(connection):
34
    ws = connection._transport
35
    assert not ws.closed
36
    assert not connection.closed
37
    await connection.close()
38
    assert connection.closed
39
    assert ws.closed
40
41
42
@pytest.mark.asyncio
43
async def test_conn_context_manager(connection):
44
    async with connection:
45
        assert not connection.closed
46
    assert connection.closed
47
48
49
@pytest.mark.asyncio
50
async def test_submit(connection):
51
    async with connection:
52
        message = request.RequestMessage(
53
            processor='', op='eval',
54
            args={'gremlin': '1 + 1'})
55
        stream = await connection.submit(message)
56
        results = []
57
        async for msg in stream:
58
            results.append(msg)
59
        assert len(results) == 1
60
        assert results[0] == 2
61
62
63
@pytest.mark.asyncio
64
async def test_204_empty_stream(connection):
65
    resp = False
66
    async with connection:
67
        message = request.RequestMessage(
68
            processor='', op='eval',
69
            args={'gremlin': 'g.V().has("unlikely", "even less likely")'})
70
        stream = await connection.submit(message)
71
        async for msg in stream:
72
            resp = True
73
    assert not resp
74
75
76
@pytest.mark.asyncio
77
async def test_server_error(connection):
78
    async with connection:
79
        message = request.RequestMessage(
80
            processor='', op='eval',
81
            args={'gremlin': 'g. V jla;sdf'})
82
        stream = await connection.submit(message)
83
        with pytest.raises(exception.GremlinServerError):
84
            async for msg in stream:
85
                pass
86
87
88
@pytest.mark.asyncio
89
async def test_cant_connect(event_loop, gremlin_server, unused_server_url):
90
    with pytest.raises(Exception):
91
        await gremlin_server.get_connection(unused_server_url, event_loop)
92
93
94
@pytest.mark.asyncio
95
async def test_resp_queue_removed_from_conn(connection):
96
    async with connection:
97
        message = request.RequestMessage(
98
            processor='', op='eval',
99
            args={'gremlin': '1 + 1'})
100
        stream = await connection.submit(message)
101
        async for msg in stream:
102
            pass
103
        await asyncio.sleep(0)
104
        assert stream not in list(connection._result_sets.values())
105
106
107
@pytest.mark.asyncio
108
async def test_stream_done(connection):
109
    async with connection:
110
        message = request.RequestMessage(
111
            processor='', op='eval',
112
            args={'gremlin': '1 + 1'})
113
        stream = await connection.submit(message)
114
        async for msg in stream:
115
            pass
116
        assert stream.done
117
118
@pytest.mark.asyncio
119
async def test_connection_response_timeout(connection):
120
    async with connection:
121
        connection._response_timeout = 0.0000001
122
        with pytest.raises(exception.ResponseTimeoutError):
123
            message = request.RequestMessage(
124
                processor='', op='eval',
125
                args={'gremlin': '1 + 1'})
126
            stream = await connection.submit(message)
127
            async for msg in stream:
128
                pass
129
130
131
# @pytest.mark.asyncio
132
# async def test_authenticated_connection(event_loop, unused_tcp_port):
133
#     authentication_request_queue = asyncio.Queue(loop=event_loop)
134
#
135
#     username, password = 'test_username', 'test_password'
136
#
137
#     async def fake_auth(request):
138
#         ws = web.WebSocketResponse()
139
#         await ws.prepare(request)
140
#
141
#         msg = await ws.receive()
142
#         data = json.loads(msg.data.decode()[17:])
143
#         await authentication_request_queue.put(data)
144
#
145
#         auth_resp = {
146
#             "requestId": data["requestId"],
147
#             "status": {"code": 407, "attributes": {}, "message": ""},
148
#             "result": {"data": None, "meta": {}}
149
#         }
150
#         resp_payload = json.dumps(auth_resp)
151
#         ws.send_str(resp_payload)
152
#
153
#         auth_msg = await ws.receive()
154
#         auth_msg_data = json.loads(auth_msg.data.decode()[17:])
155
#         await authentication_request_queue.put(auth_msg_data)
156
#
157
#         return ws
158
#
159
#     aiohttp_app = web.Application(loop=event_loop)
160
#     aiohttp_app.router.add_route('GET', '/gremlin', fake_auth)
161
#     handler = aiohttp_app.make_handler()
162
#     srv = await event_loop.create_server(handler, '0.0.0.0', unused_tcp_port)
163
#
164
#     async with aiohttp.ClientSession(loop=event_loop) as session:
165
#         url = 'ws://0.0.0.0:{}/gremlin'.format(unused_tcp_port)
166
#         async with session.ws_connect(url) as ws_client:
167
#             connection = driver.Connection(
168
#                 url=url, ws=ws_client, loop=event_loop, client_session=session,
169
#                 username=username, password=password, max_inflight=64, response_timeout=None,
170
#                 message_serializer=serializer.GraphSONMessageSerializer,
171
#                 provider=provider.TinkerGraph
172
#             )
173
#             task = event_loop.create_task(connection.submit("1+1"))
174
#             initial_request = await authentication_request_queue.get()
175
#             auth_request = await authentication_request_queue.get()
176
#             print(auth_request)
177
#             auth_str = auth_request['args']['sasl']
178
#             assert base64.b64decode(auth_str).decode().split('\x00')[1:] == [username, password]
179
#             assert auth_request['requestId'] == initial_request['requestId']
180
#             resp = await task
181
#             resp.close()
182
#
183
#             await connection.close()
184