| 6 | |
| 7 | |
| 8 | def redirects(request: httpx.Request) -> httpx.Response: |
| 9 | if request.url.scheme not in ("http", "https"): |
| 10 | raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.") |
| 11 | |
| 12 | if request.url.path == "/redirect_301": |
| 13 | status_code = httpx.codes.MOVED_PERMANENTLY |
| 14 | content = b"<a href='https://example.org/'>here</a>" |
| 15 | headers = {"location": "https://example.org/"} |
| 16 | return httpx.Response(status_code, headers=headers, content=content) |
| 17 | |
| 18 | elif request.url.path == "/redirect_302": |
| 19 | status_code = httpx.codes.FOUND |
| 20 | headers = {"location": "https://example.org/"} |
| 21 | return httpx.Response(status_code, headers=headers) |
| 22 | |
| 23 | elif request.url.path == "/redirect_303": |
| 24 | status_code = httpx.codes.SEE_OTHER |
| 25 | headers = {"location": "https://example.org/"} |
| 26 | return httpx.Response(status_code, headers=headers) |
| 27 | |
| 28 | elif request.url.path == "/relative_redirect": |
| 29 | status_code = httpx.codes.SEE_OTHER |
| 30 | headers = {"location": "/"} |
| 31 | return httpx.Response(status_code, headers=headers) |
| 32 | |
| 33 | elif request.url.path == "/malformed_redirect": |
| 34 | status_code = httpx.codes.SEE_OTHER |
| 35 | headers = {"location": "https://:443/"} |
| 36 | return httpx.Response(status_code, headers=headers) |
| 37 | |
| 38 | elif request.url.path == "/invalid_redirect": |
| 39 | status_code = httpx.codes.SEE_OTHER |
| 40 | raw_headers = [(b"location", "https://😇/".encode("utf-8"))] |
| 41 | return httpx.Response(status_code, headers=raw_headers) |
| 42 | |
| 43 | elif request.url.path == "/no_scheme_redirect": |
| 44 | status_code = httpx.codes.SEE_OTHER |
| 45 | headers = {"location": "//example.org/"} |
| 46 | return httpx.Response(status_code, headers=headers) |
| 47 | |
| 48 | elif request.url.path == "/multiple_redirects": |
| 49 | params = httpx.QueryParams(request.url.query) |
| 50 | count = int(params.get("count", "0")) |
| 51 | redirect_count = count - 1 |
| 52 | status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK |
| 53 | if count: |
| 54 | location = "/multiple_redirects" |
| 55 | if redirect_count: |
| 56 | location += f"?count={redirect_count}" |
| 57 | headers = {"location": location} |
| 58 | else: |
| 59 | headers = {} |
| 60 | return httpx.Response(status_code, headers=headers) |
| 61 | |
| 62 | if request.url.path == "/redirect_loop": |
| 63 | status_code = httpx.codes.SEE_OTHER |
| 64 | headers = {"location": "/redirect_loop"} |
| 65 | return httpx.Response(status_code, headers=headers) |