| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
# License, v. 2.0. If a copy of the MPL was not distributed with this file, |
| 5 |
# You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
import collections |
| 8 |
import json |
| 9 |
import os |
| 10 |
from urllib.error import HTTPError |
| 11 |
from urllib.request import ( |
| 12 |
HTTPHandler, |
| 13 |
ProxyHandler, |
| 14 |
Request, |
| 15 |
build_opener, |
| 16 |
install_opener, |
| 17 |
urlopen, |
| 18 |
) |
| 19 |
|
| 20 |
import mozhttpd |
| 21 |
import mozunit |
| 22 |
import pytest |
| 23 |
from six import ensure_binary, ensure_str |
| 24 |
|
| 25 |
|
| 26 |
def httpd_url(httpd, path, querystr=None): |
| 27 |
"""Return the URL to a started MozHttpd server for the given info.""" |
| 28 |
|
| 29 |
url = f"http://127.0.0.1:{httpd.httpd.server_port}{path}" |
| 30 |
|
| 31 |
if querystr is not None: |
| 32 |
url = f"{url}?{querystr}" |
| 33 |
|
| 34 |
return url |
| 35 |
|
| 36 |
|
| 37 |
@pytest.fixture(name="num_requests") |
| 38 |
def fixture_num_requests(): |
| 39 |
"""Return a defaultdict to count requests to HTTP handlers.""" |
| 40 |
return collections.defaultdict(int) |
| 41 |
|
| 42 |
|
| 43 |
@pytest.fixture(name="try_get") |
| 44 |
def fixture_try_get(num_requests): |
| 45 |
"""Return a function to try GET requests to the server.""" |
| 46 |
|
| 47 |
def try_get(httpd, querystr): |
| 48 |
"""Try GET requests to the server.""" |
| 49 |
|
| 50 |
num_requests["get_handler"] = 0 |
| 51 |
|
| 52 |
f = urlopen(httpd_url(httpd, "/api/resource/1", querystr)) |
| 53 |
|
| 54 |
assert f.getcode() == 200 |
| 55 |
assert json.loads(f.read()) == {"called": 1, "id": "1", "query": querystr} |
| 56 |
assert num_requests["get_handler"] == 1 |
| 57 |
|
| 58 |
return try_get |
| 59 |
|
| 60 |
|
| 61 |
@pytest.fixture(name="try_post") |
| 62 |
def fixture_try_post(num_requests): |
| 63 |
"""Return a function to try POST calls to the server.""" |
| 64 |
|
| 65 |
def try_post(httpd, querystr): |
| 66 |
"""Try POST calls to the server.""" |
| 67 |
|
| 68 |
num_requests["post_handler"] = 0 |
| 69 |
|
| 70 |
postdata = {"hamburgers": "1234"} |
| 71 |
|
| 72 |
f = urlopen( |
| 73 |
httpd_url(httpd, "/api/resource/", querystr), |
| 74 |
data=ensure_binary(json.dumps(postdata)), |
| 75 |
) |
| 76 |
|
| 77 |
assert f.getcode() == 201 |
| 78 |
assert json.loads(f.read()) == { |
| 79 |
"called": 1, |
| 80 |
"data": postdata, |
| 81 |
"query": querystr, |
| 82 |
} |
| 83 |
assert num_requests["post_handler"] == 1 |
| 84 |
|
| 85 |
return try_post |
| 86 |
|
| 87 |
|
| 88 |
@pytest.fixture(name="try_del") |
| 89 |
def fixture_try_del(num_requests): |
| 90 |
"""Return a function to try DEL calls to the server.""" |
| 91 |
|
| 92 |
def try_del(httpd, querystr): |
| 93 |
"""Try DEL calls to the server.""" |
| 94 |
|
| 95 |
num_requests["del_handler"] = 0 |
| 96 |
|
| 97 |
opener = build_opener(HTTPHandler) |
| 98 |
request = Request(httpd_url(httpd, "/api/resource/1", querystr)) |
| 99 |
request.get_method = lambda: "DEL" |
| 100 |
f = opener.open(request) |
| 101 |
|
| 102 |
assert f.getcode() == 200 |
| 103 |
assert json.loads(f.read()) == {"called": 1, "id": "1", "query": querystr} |
| 104 |
assert num_requests["del_handler"] == 1 |
| 105 |
|
| 106 |
return try_del |
| 107 |
|
| 108 |
|
| 109 |
@pytest.fixture(name="httpd_no_urlhandlers") |
| 110 |
def fixture_httpd_no_urlhandlers(): |
| 111 |
"""Yields a started MozHttpd server with no URL handlers.""" |
| 112 |
httpd = mozhttpd.MozHttpd(port=0) |
| 113 |
httpd.start(block=False) |
| 114 |
yield httpd |
| 115 |
httpd.stop() |
| 116 |
|
| 117 |
|
| 118 |
@pytest.fixture(name="httpd_with_docroot") |
| 119 |
def fixture_httpd_with_docroot(num_requests): |
| 120 |
"""Yields a started MozHttpd server with docroot set.""" |
| 121 |
|
| 122 |
@mozhttpd.handlers.json_response |
| 123 |
def get_handler(request, objid): |
| 124 |
"""Handler for HTTP GET requests.""" |
| 125 |
|
| 126 |
num_requests["get_handler"] += 1 |
| 127 |
|
| 128 |
return ( |
| 129 |
200, |
| 130 |
{ |
| 131 |
"called": num_requests["get_handler"], |
| 132 |
"id": objid, |
| 133 |
"query": request.query, |
| 134 |
}, |
| 135 |
) |
| 136 |
|
| 137 |
httpd = mozhttpd.MozHttpd( |
| 138 |
port=0, |
| 139 |
docroot=os.path.dirname(os.path.abspath(__file__)), |
| 140 |
urlhandlers=[ |
| 141 |
{ |
| 142 |
"method": "GET", |
| 143 |
"path": "/api/resource/([^/]+)/?", |
| 144 |
"function": get_handler, |
| 145 |
} |
| 146 |
], |
| 147 |
) |
| 148 |
|
| 149 |
httpd.start(block=False) |
| 150 |
yield httpd |
| 151 |
httpd.stop() |
| 152 |
|
| 153 |
|
| 154 |
@pytest.fixture(name="httpd") |
| 155 |
def fixture_httpd(num_requests): |
| 156 |
"""Yield a started MozHttpd server.""" |
| 157 |
|
| 158 |
@mozhttpd.handlers.json_response |
| 159 |
def get_handler(request, objid): |
| 160 |
"""Handler for HTTP GET requests.""" |
| 161 |
|
| 162 |
num_requests["get_handler"] += 1 |
| 163 |
|
| 164 |
return ( |
| 165 |
200, |
| 166 |
{ |
| 167 |
"called": num_requests["get_handler"], |
| 168 |
"id": objid, |
| 169 |
"query": request.query, |
| 170 |
}, |
| 171 |
) |
| 172 |
|
| 173 |
@mozhttpd.handlers.json_response |
| 174 |
def post_handler(request): |
| 175 |
"""Handler for HTTP POST requests.""" |
| 176 |
|
| 177 |
num_requests["post_handler"] += 1 |
| 178 |
|
| 179 |
return ( |
| 180 |
201, |
| 181 |
{ |
| 182 |
"called": num_requests["post_handler"], |
| 183 |
"data": json.loads(request.body), |
| 184 |
"query": request.query, |
| 185 |
}, |
| 186 |
) |
| 187 |
|
| 188 |
@mozhttpd.handlers.json_response |
| 189 |
def del_handler(request, objid): |
| 190 |
"""Handler for HTTP DEL requests.""" |
| 191 |
|
| 192 |
num_requests["del_handler"] += 1 |
| 193 |
|
| 194 |
return ( |
| 195 |
200, |
| 196 |
{ |
| 197 |
"called": num_requests["del_handler"], |
| 198 |
"id": objid, |
| 199 |
"query": request.query, |
| 200 |
}, |
| 201 |
) |
| 202 |
|
| 203 |
httpd = mozhttpd.MozHttpd( |
| 204 |
port=0, |
| 205 |
urlhandlers=[ |
| 206 |
{ |
| 207 |
"method": "GET", |
| 208 |
"path": "/api/resource/([^/]+)/?", |
| 209 |
"function": get_handler, |
| 210 |
}, |
| 211 |
{ |
| 212 |
"method": "POST", |
| 213 |
"path": "/api/resource/?", |
| 214 |
"function": post_handler, |
| 215 |
}, |
| 216 |
{ |
| 217 |
"method": "DEL", |
| 218 |
"path": "/api/resource/([^/]+)/?", |
| 219 |
"function": del_handler, |
| 220 |
}, |
| 221 |
], |
| 222 |
) |
| 223 |
|
| 224 |
httpd.start(block=False) |
| 225 |
yield httpd |
| 226 |
httpd.stop() |
| 227 |
|
| 228 |
|
| 229 |
def test_api(httpd, try_get, try_post, try_del): |
| 230 |
# GET requests |
| 231 |
try_get(httpd, "") |
| 232 |
try_get(httpd, "?foo=bar") |
| 233 |
|
| 234 |
# POST requests |
| 235 |
try_post(httpd, "") |
| 236 |
try_post(httpd, "?foo=bar") |
| 237 |
|
| 238 |
# DEL requests |
| 239 |
try_del(httpd, "") |
| 240 |
try_del(httpd, "?foo=bar") |
| 241 |
|
| 242 |
# GET: By default we don't serve any files if we just define an API |
| 243 |
with pytest.raises(HTTPError) as exc_info: |
| 244 |
urlopen(httpd_url(httpd, "/")) |
| 245 |
|
| 246 |
assert exc_info.value.code == 404 |
| 247 |
|
| 248 |
|
| 249 |
def test_nonexistent_resources(httpd_no_urlhandlers): |
| 250 |
# GET: Return 404 for non-existent endpoint |
| 251 |
with pytest.raises(HTTPError) as excinfo: |
| 252 |
urlopen(httpd_url(httpd_no_urlhandlers, "/api/resource/")) |
| 253 |
assert excinfo.value.code == 404 |
| 254 |
|
| 255 |
# POST: POST should also return 404 |
| 256 |
with pytest.raises(HTTPError) as excinfo: |
| 257 |
urlopen( |
| 258 |
httpd_url(httpd_no_urlhandlers, "/api/resource/"), |
| 259 |
data=ensure_binary(json.dumps({})), |
| 260 |
) |
| 261 |
assert excinfo.value.code == 404 |
| 262 |
|
| 263 |
# DEL: DEL should also return 404 |
| 264 |
opener = build_opener(HTTPHandler) |
| 265 |
request = Request(httpd_url(httpd_no_urlhandlers, "/api/resource/")) |
| 266 |
request.get_method = lambda: "DEL" |
| 267 |
|
| 268 |
with pytest.raises(HTTPError) as excinfo: |
| 269 |
opener.open(request) |
| 270 |
assert excinfo.value.code == 404 |
| 271 |
|
| 272 |
|
| 273 |
def test_api_with_docroot(httpd_with_docroot, try_get): |
| 274 |
f = urlopen(httpd_url(httpd_with_docroot, "/")) |
| 275 |
assert f.getcode() == 200 |
| 276 |
assert "Directory listing for" in ensure_str(f.read()) |
| 277 |
|
| 278 |
# Make sure API methods still work |
| 279 |
try_get(httpd_with_docroot, "") |
| 280 |
try_get(httpd_with_docroot, "?foo=bar") |
| 281 |
|
| 282 |
|
| 283 |
def index_contents(host): |
| 284 |
"""Return the expected index contents for the given host.""" |
| 285 |
return f"{host} index" |
| 286 |
|
| 287 |
|
| 288 |
@pytest.fixture(name="hosts") |
| 289 |
def fixture_hosts(): |
| 290 |
"""Returns a tuple of hosts.""" |
| 291 |
return ("mozilla.com", "mozilla.org") |
| 292 |
|
| 293 |
|
| 294 |
@pytest.fixture(name="docroot") |
| 295 |
def fixture_docroot(tmpdir): |
| 296 |
"""Returns a path object to a temporary docroot directory.""" |
| 297 |
docroot = tmpdir.mkdir("docroot") |
| 298 |
index_file = docroot.join("index.html") |
| 299 |
index_file.write(index_contents("*")) |
| 300 |
|
| 301 |
yield docroot |
| 302 |
|
| 303 |
docroot.remove() |
| 304 |
|
| 305 |
|
| 306 |
@pytest.fixture(name="httpd_with_proxy_handler") |
| 307 |
def fixture_httpd_with_proxy_handler(docroot): |
| 308 |
"""Yields a started MozHttpd server for the proxy test.""" |
| 309 |
|
| 310 |
httpd = mozhttpd.MozHttpd(port=0, docroot=str(docroot)) |
| 311 |
httpd.start(block=False) |
| 312 |
|
| 313 |
port = httpd.httpd.server_port |
| 314 |
proxy_support = ProxyHandler( |
| 315 |
{ |
| 316 |
"http": f"http://127.0.0.1:{port:d}", |
| 317 |
} |
| 318 |
) |
| 319 |
install_opener(build_opener(proxy_support)) |
| 320 |
|
| 321 |
yield httpd |
| 322 |
|
| 323 |
httpd.stop() |
| 324 |
|
| 325 |
# Reset proxy opener in case it changed |
| 326 |
install_opener(None) |
| 327 |
|
| 328 |
|
| 329 |
def test_proxy(httpd_with_proxy_handler, hosts): |
| 330 |
for host in hosts: |
| 331 |
f = urlopen(f"http://{host}/") |
| 332 |
assert f.getcode() == 200 |
| 333 |
assert f.read() == ensure_binary(index_contents("*")) |
| 334 |
|
| 335 |
|
| 336 |
@pytest.fixture(name="httpd_with_proxy_host_dirs") |
| 337 |
def fixture_httpd_with_proxy_host_dirs(docroot, hosts): |
| 338 |
for host in hosts: |
| 339 |
index_file = docroot.mkdir(host).join("index.html") |
| 340 |
index_file.write(index_contents(host)) |
| 341 |
|
| 342 |
httpd = mozhttpd.MozHttpd(port=0, docroot=str(docroot), proxy_host_dirs=True) |
| 343 |
|
| 344 |
httpd.start(block=False) |
| 345 |
|
| 346 |
port = httpd.httpd.server_port |
| 347 |
proxy_support = ProxyHandler({"http": f"http://127.0.0.1:{port:d}"}) |
| 348 |
install_opener(build_opener(proxy_support)) |
| 349 |
|
| 350 |
yield httpd |
| 351 |
|
| 352 |
httpd.stop() |
| 353 |
|
| 354 |
# Reset proxy opener in case it changed |
| 355 |
install_opener(None) |
| 356 |
|
| 357 |
|
| 358 |
def test_proxy_separate_directories(httpd_with_proxy_host_dirs, hosts): |
| 359 |
for host in hosts: |
| 360 |
f = urlopen(f"http://{host}/") |
| 361 |
assert f.getcode() == 200 |
| 362 |
assert f.read() == ensure_binary(index_contents(host)) |
| 363 |
|
| 364 |
unproxied_host = "notmozilla.org" |
| 365 |
|
| 366 |
with pytest.raises(HTTPError) as excinfo: |
| 367 |
urlopen(f"http://{unproxied_host}/") |
| 368 |
|
| 369 |
assert excinfo.value.code == 404 |
| 370 |
|
| 371 |
|
| 372 |
if __name__ == "__main__": |
| 373 |
mozunit.main() |