|
| 1 | +import tornado.web |
| 2 | +from tornado.testing import AsyncHTTPTestCase |
| 3 | + |
| 4 | +from nodenorm.handlers.base import NodeNormalizationBaseHandler |
| 5 | + |
| 6 | +ORIGIN = "https://translatorsri.github.io" |
| 7 | + |
| 8 | + |
| 9 | +class PreflightHandler(NodeNormalizationBaseHandler): |
| 10 | + async def get(self): |
| 11 | + self.finish({"ok": True}) |
| 12 | + |
| 13 | + |
| 14 | +def assert_cors_headers(headers, allowed_headers="*"): |
| 15 | + assert headers["Access-Control-Allow-Origin"] == "*" |
| 16 | + assert "Access-Control-Allow-Credentials" not in headers |
| 17 | + assert headers["Access-Control-Allow-Methods"] == "GET, POST, HEAD, OPTIONS" |
| 18 | + assert headers["Access-Control-Allow-Headers"] == allowed_headers |
| 19 | + assert headers["Access-Control-Max-Age"] == "600" |
| 20 | + |
| 21 | + |
| 22 | +class TestCorsHeaders(AsyncHTTPTestCase): |
| 23 | + def get_app(self) -> tornado.web.Application: |
| 24 | + return tornado.web.Application( |
| 25 | + [ |
| 26 | + (r"/version", PreflightHandler), |
| 27 | + (r"/get_normalized_nodes", PreflightHandler), |
| 28 | + ] |
| 29 | + ) |
| 30 | + |
| 31 | + def test_get_response_includes_cors_headers_for_browser_origin(self): |
| 32 | + response = self.fetch("/version", headers={"Origin": ORIGIN}) |
| 33 | + |
| 34 | + assert response.code == 200 |
| 35 | + assert_cors_headers(response.headers) |
| 36 | + |
| 37 | + def test_preflight_returns_cors_headers(self): |
| 38 | + response = self.fetch( |
| 39 | + "/get_normalized_nodes", |
| 40 | + method="OPTIONS", |
| 41 | + headers={ |
| 42 | + "Origin": ORIGIN, |
| 43 | + "Access-Control-Request-Method": "POST", |
| 44 | + "Access-Control-Request-Headers": "content-type", |
| 45 | + }, |
| 46 | + ) |
| 47 | + |
| 48 | + assert response.code == 200 |
| 49 | + assert response.body == b"" |
| 50 | + assert_cors_headers(response.headers, "content-type") |
0 commit comments