|
| 1 | +import importlib.util |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import tornado.web |
| 5 | +from tornado.testing import AsyncHTTPTestCase |
| 6 | + |
| 7 | + |
| 8 | +ORIGIN = "https://translatorsri.github.io" |
| 9 | +BASE_HANDLER_PATH = Path(__file__).parents[1] / "src" / "nodenorm" / "handlers" / "base.py" |
| 10 | + |
| 11 | + |
| 12 | +def load_base_handler(): |
| 13 | + spec = importlib.util.spec_from_file_location("_nodenorm_base_handler_under_test", BASE_HANDLER_PATH) |
| 14 | + module = importlib.util.module_from_spec(spec) |
| 15 | + spec.loader.exec_module(module) |
| 16 | + return module.NodeNormalizationBaseHandler |
| 17 | + |
| 18 | + |
| 19 | +NodeNormalizationBaseHandler = load_base_handler() |
| 20 | + |
| 21 | + |
| 22 | +class PreflightHandler(NodeNormalizationBaseHandler): |
| 23 | + async def get(self): |
| 24 | + self.finish({"ok": True}) |
| 25 | + |
| 26 | + |
| 27 | +def assert_cors_headers(headers, allowed_headers="*"): |
| 28 | + assert headers["Access-Control-Allow-Origin"] == ORIGIN |
| 29 | + assert headers["Access-Control-Allow-Credentials"] == "true" |
| 30 | + assert headers["Access-Control-Allow-Methods"] == "GET, POST, HEAD, OPTIONS" |
| 31 | + assert headers["Access-Control-Allow-Headers"] == allowed_headers |
| 32 | + assert headers["Access-Control-Max-Age"] == "600" |
| 33 | + assert headers["Vary"] == "Origin" |
| 34 | + |
| 35 | + |
| 36 | +class TestCorsHeaders(AsyncHTTPTestCase): |
| 37 | + def get_app(self) -> tornado.web.Application: |
| 38 | + return tornado.web.Application( |
| 39 | + [ |
| 40 | + (r"/version", PreflightHandler), |
| 41 | + (r"/get_normalized_nodes", PreflightHandler), |
| 42 | + ] |
| 43 | + ) |
| 44 | + |
| 45 | + def test_get_response_includes_cors_headers_for_browser_origin(self): |
| 46 | + response = self.fetch("/version", headers={"Origin": ORIGIN}) |
| 47 | + |
| 48 | + assert response.code == 200 |
| 49 | + assert_cors_headers(response.headers) |
| 50 | + |
| 51 | + def test_preflight_returns_cors_headers(self): |
| 52 | + response = self.fetch( |
| 53 | + "/get_normalized_nodes", |
| 54 | + method="OPTIONS", |
| 55 | + headers={ |
| 56 | + "Origin": ORIGIN, |
| 57 | + "Access-Control-Request-Method": "POST", |
| 58 | + "Access-Control-Request-Headers": "content-type", |
| 59 | + }, |
| 60 | + ) |
| 61 | + |
| 62 | + assert response.code == 200 |
| 63 | + assert response.body == b"" |
| 64 | + assert_cors_headers(response.headers, "content-type") |
0 commit comments