-
Notifications
You must be signed in to change notification settings - Fork 28
/
test_http_mocking.py
267 lines (197 loc) · 6.91 KB
/
test_http_mocking.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# -*- coding: utf-8 -*-
# (c) 2020 Richard Pobering <[email protected]>
# (c) 2020 Andreas Motl <[email protected]>
# License: GNU General Public License, Version 3
import time
import json
import socket
import pytest
import requests
import httpretty
from mocket import mocketize, Mocket
from mocket.mockhttp import Entry
from urllib.parse import urlparse, splitport
from pytest_httpserver.pytest_plugin import Plugin, PluginHTTPServer
@mocketize
@pytest.mark.httpmock
def test_mocket_cpython_requests():
"""
Using the ``requests`` module works perfectly.
"""
# Define HTTP request details.
url = 'http://127.0.0.1/api/data'
data = {'hello': 'world'}
# Mock HTTP conversation.
Entry.single_register(Entry.POST, url)
# Invoke HTTP request.
requests.post(url, json=data)
# Proof that worked.
assert Mocket.last_request().body == json.dumps(data)
@mocketize
@pytest.mark.httpmock
@pytest.mark.xfail(raises=ValueError)
def test_mocket_socket():
"""
Demonstrate HTTP streaming to Mocket's "mockhttp".
The error is::
self = <mocket.mockhttp.Request object at 0x108cf74c0>, data = b'POST /api/data HTTP/1.0\r\n'
def __init__(self, data):
> _, self.body = decode_from_bytes(data).split('\r\n\r\n', 1)
E ValueError: not enough values to unpack (expected 2, got 1)
.venv3/lib/python3.8/site-packages/mocket/mockhttp.py:23: ValueError
The reason is that ``data`` is essentially::
b'POST /api/data HTTP/1.0\r\n'
which well fails on being split by ``\r\n\r\n`` appropriately.
So, when receiving a streamed response, Mocket's "mockhttp"
should not expect the data to be sent en bloc.
"""
# Define HTTP request details.
method = 'POST'
url = 'http://127.0.0.1/api/data'
data = {'hello': 'world'}
# Mock HTTP conversation.
Entry.single_register(Entry.POST, url)
# Invoke HTTP request.
send_request(url, method, json=data)
# Proof that worked.
assert Mocket.last_request().body == json.dumps(data)
@httpretty.activate
@pytest.mark.httpmock
def test_httpretty_cpython_requests():
"""
Using the ``requests`` module works perfectly.
"""
# Define HTTP request details.
url = 'http://127.0.0.1/api/data'
data = {'hello': 'world'}
# Mock HTTP conversation.
httpretty.register_uri(
httpretty.POST,
url,
body=json.dumps({'status': 'ok'})
)
# Invoke HTTP request.
response = requests.post(url, json=data)
# Proof everything is in place.
# Check response.
assert response.json() == {'status': 'ok'}
# Check request.
assert len(httpretty.latest_requests()) == 1
assert httpretty.last_request() == httpretty.latest_requests()[0]
assert httpretty.last_request().body == json.dumps(data).encode()
@httpretty.activate
@pytest.mark.httpmock
@pytest.mark.xfail(raises=RuntimeError)
def test_httpretty_socket():
"""
Using raw sockets will also fail with ``httpretty``.
"""
# Define HTTP request details.
method = 'POST'
url = 'http://127.0.0.1/api/data'
data = {'hello': 'world'}
# Mock HTTP conversation.
httpretty.register_uri(
httpretty.POST,
url,
body=json.dumps({'status': 'ok'})
)
# Invoke HTTP request.
send_request(url, method, json=data)
# Proof everything is in place.
# Check response.
#assert response.json() == {'status': 'ok'}
# Check request.
assert len(httpretty.latest_requests()) == 1
assert httpretty.last_request() == httpretty.latest_requests()[0]
assert httpretty.last_request().body == json.dumps(data).encode()
@pytest.mark.httpmock
def test_httpserver_cpython_requests(httpserver_ipv4):
"""
Using the ``requests`` module works perfectly.
"""
httpserver = httpserver_ipv4
# Define HTTP conversation details.
request_data = {'hello': 'world'}
response_data = {'status': 'ok'}
# Mock HTTP conversation.
httpserver.expect_request("/api/data").respond_with_json(response_data)
# Invoke HTTP request.
url = httpserver.url_for("/api/data")
requests.post(url, json=request_data)
# Proof that worked.
request, response = httpserver.log[0]
assert request.get_data() == json.dumps(request_data).encode()
assert response.get_data() == json.dumps(response_data, indent=4).encode()
@pytest.mark.httpmock
def test_httpserver_socket(httpserver_ipv4):
"""
This works better, but occasionally still fails with::
AssertionError: pytest-httpserver didn't capture any request
"""
httpserver = httpserver_ipv4
# Define HTTP request details.
method = 'POST'
data = {'hello': 'world'}
# Mock HTTP conversation.
httpserver.expect_request("/api/data").respond_with_json({'status': 'ok'})
# Invoke HTTP request.
url = httpserver.url_for("/api/data")
send_request(url, method, json=data)
time.sleep(0.2)
# Proof that worked.
assert len(httpserver.log) == 1, "pytest-httpserver didn't capture any request"
request, response = httpserver.log[0]
assert request.get_data() == json.dumps(data).encode()
def send_request(url, method, data=None, json=None):
#socket.setdefaulttimeout(2.0)
uri = urlparse(url)
host, port = splitport(uri.netloc)
port = port or 80
path = uri.path
address = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
sock = socket.socket(address[0], address[1], address[2])
sock.connect(address[-1])
if json is not None:
import json as json_module
data = json_module.dumps(json)
method = method.encode()
host = host.encode()
path = path.encode()
data = data.encode()
sock.send(b"%s %s HTTP/1.0\r\n" % (method, path))
sock.send(b"Host: %s\r\n" % host)
sock.send(b"Content-Type: application/json\r\n")
sock.send(b"Content-Length: %d\r\n" % len(data))
sock.send(b"Connection: close\r\n\r\n")
sock.send(data)
def send_request_stream(url, method, data):
uri = urlparse(url)
host, port = splitport(uri.netloc)
port = port or 80
path = uri.path
address = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
sock = socket.socket(address[0], address[1], address[2])
sock.connect(address[-1])
method = method.encode()
host = host.encode()
path = path.encode()
data = data.encode()
sock.makefile(mode='rwb')
sock.write(b"%s %s HTTP/1.0\r\n" % (method, path))
sock.write(b"Host: %s\r\n" % host)
sock.write(b"Content-Type: application/json\r\n")
sock.write(b"Content-Length: %d\r\n" % len(data))
sock.write(b"Connection: close\r\n\r\n")
sock.write(data)
@pytest.fixture(scope='function')
def httpserver_ipv4():
if Plugin.SERVER:
Plugin.SERVER.clear()
yield Plugin.SERVER
return
server = PluginHTTPServer(host='127.0.0.1', port=8888)
server.start()
#time.sleep(0.1)
yield server
server.stop()