├── __init__.py ├── test-image.png ├── .gitignore ├── pyproject.toml ├── SECURITY.md ├── setup.cfg ├── LICENSE.md ├── .github └── workflows │ ├── release.yml │ ├── codeql-analysis.yml │ └── ci.yml ├── UNLICENSE.md ├── README.md └── thttp.py /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sesh/thttp/main/test-image.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | htmlcov 3 | .coverage 4 | build 5 | *.egg-info 6 | dist -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=42"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.ruff] 6 | line-length = 120 7 | 8 | [tool.black] 9 | line-length = 120 10 | 11 | [tool.isort] 12 | profile = "black" 13 | 14 | [tool.coverage.report] 15 | include = ["thttp.py"] 16 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Only the latest code available via Github is officially supported. 6 | This library is small, you should audit the code and ensure that it's of a similar quality to the rest of the code in your project. 7 | 8 | ## Reporting a Vulnerability 9 | 10 | Security issues can be reported to security@brntn.me. 11 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = thttp 3 | version = 1.3.0 4 | author = Brenton Cleeland 5 | author_email = brenton@brntn.me 6 | description = An incredibly lightweight wrapper around urllib 7 | long_description = file: README.md 8 | long_description_content_type = text/markdown 9 | url = https://github.com/sesh/thttp 10 | project_urls = 11 | Bug Tracker = https://github.com/sesh/thttp/issues 12 | classifiers = 13 | Programming Language :: Python :: 3 14 | 15 | [options] 16 | packages = . 17 | python_requires = >=3.6 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Brenton Cleeland 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package 2 | 3 | on: 4 | release: 5 | types: [created] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | python-version: ["3.7", "3.8", "3.9", "3.10"] 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v4 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | 23 | - name: Test with unittest 24 | run: | 25 | python -m unittest thttp.py 26 | 27 | deploy: 28 | runs-on: ubuntu-latest 29 | needs: [test] 30 | steps: 31 | - uses: actions/checkout@v3 32 | 33 | - name: Set up Python 34 | uses: actions/setup-python@v4 35 | with: 36 | python-version: '3.10' 37 | 38 | - name: Install dependencies 39 | run: | 40 | pip install setuptools wheel twine build 41 | 42 | - name: Publish 43 | env: 44 | TWINE_USERNAME: __token__ 45 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 46 | run: | 47 | python -m build 48 | twine upload dist/* 49 | -------------------------------------------------------------------------------- /UNLICENSE.md: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '26 3 * * 6' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'python' ] 36 | 37 | steps: 38 | - name: Checkout repository 39 | uses: actions/checkout@v2 40 | 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v2 43 | with: 44 | languages: ${{ matrix.language }} 45 | 46 | - name: Perform CodeQL Analysis 47 | uses: github/codeql-action/analyze@v2 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # thttp 2 | 3 | `thttp` is a single file, lightweight, well-tested wrapper around `urllib` that's intended to be copied directly into your project. 4 | 5 | It's features include: 6 | 7 | - Making GET, POST, PATCH, PUT, HEAD and OPTIONS requests 8 | - Sending query parameters with your request 9 | - Encoding JSON payloads for POST, PATCH and PUT requests 10 | - Encoding form-encoded payloads for POST, PATCH and PUT request 11 | - Sending custom headers with any request 12 | - Disabling SSL certificate verification for local testing / corporate proxies 13 | - Following (or not following) redirects 14 | - Sending through a CookieJar object that can be reused between requests 15 | - Authenticating with HTTP basic auth 16 | - Specifying a custom timeout for your request 17 | - Decompressing gzipped content in the response 18 | - Loading JSON from the response 19 | - Returning error responses instead of throwing exceptions from `urllib` 20 | - `pretty()` function for printing responses 21 | - Ability to upload files using the `{"file": open("file.png", "rb")}` style 22 | 23 | Future features: 24 | 25 | - Better detection of JSON responses 26 | - Improve handling of non-utf-8 requests 27 | - Improve handling of non-utf-8 responses 28 | 29 | _Note: this project is not intended to solve all use cases that can be achieved with urllib, requests, httpx, or other HTTP libraries. The intent is to provide a lightweight tool that simplifies some of the most common use cases for developers._ 30 | 31 | 32 | ## Installation 33 | 34 | copy `thttp.py` directly into your project: 35 | 36 | ``` 37 | curl https://raw.githubusercontent.com/sesh/thttp/main/thttp.py > thttp.py 38 | ``` 39 | 40 | Or, install with `pip`: 41 | 42 | ``` 43 | python3 -m pip install thttp 44 | ``` 45 | 46 | 47 | ## Basic Usage 48 | 49 | See the tests for examples of usage, but, effectively it's as simple as: 50 | 51 | ```python 52 | from thttp import request 53 | 54 | response = request("https://httpbingo.org/get", params={"data": "empty"}) 55 | 56 | response.json 57 | # {'args': {'data': ['empty']}, 'headers': {'Accept-Encoding': ['identity'], 'Fly-Client-Ip': ['45.76.105.111'], 'Fly-Forwarded-Port': ['443'], 'Fly-Forwarded-Proto': ['https'], 'Fly-Forwarded-Ssl': ['on'], 'Fly-Region': ['hkg'], 'Fly-Request-Id': ['01F6P2WQAY1NGPRDCXV9H60XW5'], 'Host': ['httpbingo.org'], 'User-Agent': ['Python-urllib/3.8'], 'Via': ['1.1 fly.io'], 'X-Forwarded-For': ['45.76.105.111, 77.83.142.42'], 'X-Forwarded-Port': ['443'], 'X-Forwarded-Proto': ['https'], 'X-Forwarded-Ssl': ['on'], 'X-Request-Start': ['t=1622091390302198']}, 'origin': '45.76.105.111, 77.83.142.42', 'url': 'https://httpbingo.org/get?data=empty'} 58 | 59 | response.status 60 | # 200 61 | ``` 62 | 63 | 64 | ## Running the tests 65 | 66 | ```sh 67 | > python3 -m unittest thttp.py 68 | ``` 69 | 70 | And to check the coverage: 71 | 72 | ```sh 73 | > coverage run -m unittest thttp.py 74 | > coverage html && open htmlcov/index.html 75 | ``` 76 | 77 | Run `black` before committing any changes. 78 | 79 | ```sh 80 | > black thttp.py 81 | ``` 82 | 83 | 84 | ## Packaging for release 85 | 86 | ``` 87 | rm dist/* 88 | python3 -m build 89 | python3 -m twine upload dist/* 90 | ``` 91 | 92 | 93 | ## License 94 | 95 | This code is currently released under the [UNLICENSE](UNLICENSE.md) and considered public domain. 96 | If more appropriate for your usage you may consider this project released under the [MIT License](LICENSE.md). 97 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python Checks 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | python-version: ["3.8", "3.9", "3.10", "3.11"] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v4 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | 25 | - name: Install test dependencies 26 | run: | 27 | pip install -e '.[test]' 28 | 29 | - name: Test with unittest 30 | run: | 31 | python -m unittest thttp.py 32 | env: 33 | MEDIAPUB_URL: ${{ secrets.MEDIAPUB_URL }} 34 | MEDIAPUB_TOKEN: ${{ secrets.MEDIAPUB_TOKEN }} 35 | 36 | black: 37 | runs-on: ubuntu-latest 38 | 39 | steps: 40 | - uses: actions/checkout@v3 41 | 42 | - name: Set up Python 43 | uses: actions/setup-python@v4 44 | with: 45 | python-version: "3.11" 46 | 47 | - name: Install black 48 | run: | 49 | python -m pip install black 50 | 51 | - name: Run black 52 | run: | 53 | black --check . 54 | 55 | isort: 56 | runs-on: ubuntu-latest 57 | 58 | steps: 59 | - uses: actions/checkout@v3 60 | 61 | - name: Set up Python 62 | uses: actions/setup-python@v4 63 | with: 64 | python-version: "3.11" 65 | 66 | - name: Install isort 67 | run: | 68 | python -m pip install isort 69 | 70 | - name: Run isort 71 | run: | 72 | isort --check . 73 | 74 | ruff: 75 | runs-on: ubuntu-latest 76 | 77 | steps: 78 | - uses: actions/checkout@v3 79 | 80 | - name: Set up Python 81 | uses: actions/setup-python@v4 82 | with: 83 | python-version: "3.11" 84 | 85 | - name: Install ruff 86 | run: | 87 | python -m pip install ruff 88 | 89 | - name: Run ruff 90 | run: | 91 | ruff --format=github . 92 | 93 | bandit: 94 | runs-on: ubuntu-latest 95 | 96 | steps: 97 | - uses: actions/checkout@v3 98 | 99 | - name: Set up Python 100 | uses: actions/setup-python@v4 101 | with: 102 | python-version: 3 103 | 104 | - name: Install bandit 105 | run: | 106 | python -m pip install bandit 107 | 108 | - name: Run bandit scan 109 | run: | 110 | bandit -r . 111 | 112 | coverage: 113 | runs-on: ubuntu-latest 114 | steps: 115 | - uses: actions/checkout@v3 116 | 117 | - name: Set up Python 118 | uses: actions/setup-python@v4 119 | with: 120 | python-version: "3.11" 121 | 122 | - name: Install test dependencies 123 | run: | 124 | pip install -e '.[test]' 125 | 126 | - name: Install coverage.py 127 | run: | 128 | pip install coverage 129 | 130 | - name: Test with unittest 131 | run: | 132 | coverage run -m unittest thttp.py 133 | coverage report -m --fail-under=95 134 | env: 135 | MEDIAPUB_URL: ${{ secrets.MEDIAPUB_URL }} 136 | MEDIAPUB_TOKEN: ${{ secrets.MEDIAPUB_TOKEN }} 137 | -------------------------------------------------------------------------------- /thttp.py: -------------------------------------------------------------------------------- 1 | """ 2 | You may use this code under the UNLICENSE or MIT License. 3 | See README.md for details. 4 | 5 | https://github.com/sesh/thttp 6 | """ 7 | 8 | import gzip 9 | import json as json_lib 10 | import mimetypes 11 | import secrets 12 | import ssl 13 | from base64 import b64encode 14 | from collections import namedtuple 15 | from http import HTTPStatus 16 | from http.cookiejar import CookieJar 17 | from urllib.error import HTTPError, URLError 18 | from urllib.parse import urlencode 19 | from urllib.request import ( 20 | HTTPCookieProcessor, 21 | HTTPRedirectHandler, 22 | HTTPSHandler, 23 | Request, 24 | build_opener, 25 | ) 26 | 27 | Response = namedtuple("Response", "request content json status url headers cookiejar") 28 | 29 | 30 | class NoRedirect(HTTPRedirectHandler): 31 | def redirect_request(self, req, fp, code, msg, headers, newurl): 32 | return None 33 | 34 | 35 | def request( 36 | url, 37 | params={}, 38 | json=None, 39 | data=None, 40 | headers={}, 41 | method="GET", 42 | verify=True, 43 | redirect=True, 44 | cookiejar=None, 45 | basic_auth=None, 46 | timeout=None, 47 | files={}, # note: experimental 48 | ): 49 | """ 50 | Returns a (named)tuple with the following properties: 51 | - request 52 | - content 53 | - json (dict; or None) 54 | - headers (dict; all lowercase keys) 55 | - https://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive 56 | - status 57 | - url (final url, after any redirects) 58 | - cookiejar 59 | """ 60 | method = method.upper() 61 | headers = {k.lower(): v for k, v in headers.items()} # lowercase headers 62 | 63 | if params: 64 | url += "?" + urlencode(params) # build URL from query parameters 65 | 66 | if json and data: 67 | raise Exception("Cannot provide both json and data parameters") 68 | 69 | if method not in ["POST", "PATCH", "PUT"] and (json or data): 70 | raise Exception("Request method must POST, PATCH or PUT if json or data is provided") 71 | 72 | if files and method != "POST": 73 | raise Exception("Request method must be POST when uploading files") 74 | 75 | if not timeout: 76 | timeout = 60 77 | 78 | if json: # if we have json, dump it to a string and put it in our data variable 79 | headers["content-type"] = "application/json" 80 | data = json_lib.dumps(json).encode("utf-8") 81 | elif data and not isinstance(data, (str, bytes)): 82 | data = urlencode(data).encode() 83 | elif isinstance(data, str): 84 | data = data.encode() 85 | elif files: 86 | boundary = secrets.token_hex() 87 | 88 | headers["Content-Type"] = f"multipart/form-data; boundary={boundary}" 89 | data = b"" 90 | 91 | for key, file in files.items(): 92 | file_data = file.read() # okay, we want this to stay as a byte-string 93 | if isinstance(file_data, str): 94 | file_data = file_data.encode("utf-8") 95 | fn = file.name 96 | 97 | mime, _ = mimetypes.guess_type(fn) 98 | if not mime: 99 | print("Using default mimetype") 100 | mime = "application/octet-stream" 101 | 102 | data += b"--" + boundary.encode() + b"\r\n" 103 | data += b'Content-Disposition: form-data; name="' + key.encode() + b'"; filename="' + fn.encode() + b'"\r\n' 104 | data += b"Content-Type: " + mime.encode() + b"\r\n\r\n" 105 | data += file_data + b"\r\n" 106 | data += b"--" + boundary.encode() + b"--\r\n" 107 | 108 | data = data 109 | headers["Content-Length"] = len(data) 110 | 111 | if basic_auth and len(basic_auth) == 2 and "authorization" not in headers: 112 | username, password = basic_auth 113 | headers["authorization"] = f'Basic {b64encode(f"{username}:{password}".encode()).decode("ascii")}' 114 | 115 | if not cookiejar: 116 | cookiejar = CookieJar() 117 | 118 | ctx = ssl.create_default_context() 119 | if not verify: # ignore ssl errors 120 | ctx.check_hostname = False 121 | ctx.verify_mode = ssl.CERT_NONE 122 | 123 | handlers = [] 124 | handlers.append(HTTPSHandler(context=ctx)) 125 | handlers.append(HTTPCookieProcessor(cookiejar=cookiejar)) 126 | 127 | if not redirect: 128 | no_redirect = NoRedirect() 129 | handlers.append(no_redirect) 130 | 131 | opener = build_opener(*handlers) 132 | req = Request(url, data=data, headers=headers, method=method) 133 | 134 | try: 135 | with opener.open(req, timeout=timeout) as resp: 136 | status, content, resp_url = (resp.getcode(), resp.read(), resp.geturl()) 137 | headers = {k.lower(): v for k, v in list(resp.info().items())} 138 | 139 | if "gzip" in headers.get("content-encoding", ""): 140 | content = gzip.decompress(content) 141 | 142 | json = ( 143 | json_lib.loads(content) 144 | if "application/json" in headers.get("content-type", "").lower() and content 145 | else None 146 | ) 147 | except HTTPError as e: 148 | status, content, resp_url = (e.code, e.read(), e.geturl()) 149 | headers = {k.lower(): v for k, v in list(e.headers.items())} 150 | 151 | if "gzip" in headers.get("content-encoding", ""): 152 | content = gzip.decompress(content) 153 | 154 | json = ( 155 | json_lib.loads(content) 156 | if "application/json" in headers.get("content-type", "").lower() and content 157 | else None 158 | ) 159 | 160 | return Response(req, content, json, status, resp_url, headers, cookiejar) 161 | 162 | 163 | def pretty(response, headers_only=False): 164 | RESET = "\033[0m" 165 | HIGHLIGHT = "\033[34m" 166 | HTTP_STATUSES = {x.value: x.name for x in HTTPStatus} 167 | 168 | # status code 169 | print(HIGHLIGHT + str(response.status) + " " + RESET + HTTP_STATUSES.get(response.status, "")) 170 | 171 | # headers 172 | for k in sorted(response.headers.keys()): 173 | print(HIGHLIGHT + k + RESET + ": " + response.headers[k]) 174 | 175 | if headers_only: 176 | return 177 | 178 | # blank line 179 | print() 180 | 181 | # response body 182 | if response.json: 183 | print(json_lib.dumps(response.json, indent=2)) 184 | else: 185 | print(response.content.decode()) 186 | 187 | 188 | import contextlib # noqa: E402 189 | import os # noqa: E402 190 | import unittest # noqa: E402 191 | from io import StringIO # noqa: E402 192 | from unittest.mock import patch # noqa: E402 193 | 194 | 195 | class RequestTestCase(unittest.TestCase): 196 | def test_cannot_provide_json_and_data(self): 197 | with self.assertRaises(Exception): 198 | request( 199 | "https://httpbingo.org/post", 200 | json={"name": "Brenton"}, 201 | data="This is some form data", 202 | ) 203 | 204 | def test_should_fail_if_json_or_data_and_not_p_method(self): 205 | with self.assertRaises(Exception): 206 | request("https://httpbingo.org/post", json={"name": "Brenton"}) 207 | 208 | with self.assertRaises(Exception): 209 | request("https://httpbingo.org/post", json={"name": "Brenton"}, method="HEAD") 210 | 211 | def test_should_set_content_type_for_json_request(self): 212 | response = request("https://httpbingo.org/post", json={"name": "Brenton"}, method="POST") 213 | self.assertEqual(response.request.headers["Content-type"], "application/json") 214 | 215 | def test_should_work(self): 216 | response = request("https://httpbingo.org/get") 217 | self.assertEqual(response.status, 200) 218 | 219 | def test_should_create_url_from_params(self): 220 | response = request( 221 | "https://httpbingo.org/get", 222 | params={"name": "brenton", "library": "tiny-request"}, 223 | ) 224 | self.assertEqual(response.url, "https://httpbingo.org/get?name=brenton&library=tiny-request") 225 | 226 | def test_should_return_headers(self): 227 | response = request("https://httpbingo.org/response-headers", params={"Test-Header": "value"}) 228 | self.assertEqual(response.headers["test-header"], "value") 229 | 230 | def test_should_populate_json(self): 231 | response = request("https://httpbingo.org/json") 232 | self.assertTrue("slideshow" in response.json) 233 | 234 | def test_should_return_response_for_404(self): 235 | response = request("https://httpbingo.org/404") 236 | self.assertEqual(response.status, 404) 237 | self.assertTrue("application/json" in response.headers["content-type"]) 238 | 239 | def test_should_fail_with_bad_ssl(self): 240 | with self.assertRaises(URLError): 241 | request("https://expired.badssl.com/") 242 | 243 | def test_should_load_bad_ssl_with_verify_false(self): 244 | response = request("https://expired.badssl.com/", verify=False) 245 | self.assertEqual(response.status, 200) 246 | 247 | def test_should_form_encode_non_json_post_requests(self): 248 | response = request("https://httpbingo.org/post", data={"name": "test-user"}, method="POST") 249 | self.assertEqual(response.json["form"]["name"], ["test-user"]) 250 | 251 | def test_should_follow_redirect(self): 252 | response = request( 253 | "https://httpbingo.org/redirect-to", 254 | params={"url": "https://example.org/"}, 255 | ) 256 | self.assertEqual(response.url, "https://example.org/") 257 | self.assertEqual(response.status, 200) 258 | 259 | def test_should_not_follow_redirect_if_redirect_false(self): 260 | response = request( 261 | "https://httpbingo.org/redirect-to", 262 | params={"url": "https://example.org/"}, 263 | redirect=False, 264 | ) 265 | self.assertEqual(response.status, 302) 266 | 267 | def test_cookies(self): 268 | response = request( 269 | "https://httpbingo.org/cookies/set", 270 | params={"cookie": "test"}, 271 | redirect=False, 272 | ) 273 | response = request("https://httpbingo.org/cookies", cookiejar=response.cookiejar) 274 | self.assertEqual(response.json["cookie"], "test") 275 | 276 | def test_basic_auth(self): 277 | response = request("http://httpbingo.org/basic-auth/user/passwd", basic_auth=("user", "passwd")) 278 | self.assertEqual(response.json["authorized"], True) 279 | 280 | def test_should_handle_gzip(self): 281 | response = request("http://httpbingo.org/gzip", headers={"Accept-Encoding": "gzip"}) 282 | self.assertEqual(response.json["gzipped"], True) 283 | 284 | def test_should_handle_gzip_error(self): 285 | response = request("http://httpbingo.org/status/418", headers={"Accept-Encoding": "gzip"}) 286 | self.assertEqual(response.content, b"I'm a teapot!") 287 | 288 | def test_should_timeout(self): 289 | import socket 290 | 291 | with self.assertRaises((TimeoutError, socket.timeout)): 292 | request("http://httpbingo.org/delay/3", timeout=1) 293 | 294 | def test_should_handle_head_requests(self): 295 | response = request("http://httpbingo.org/head", method="HEAD") 296 | self.assertTrue(response.content == b"") 297 | 298 | def test_should_post_data_string(self): 299 | response = request( 300 | "https://ntfy.sh/thttp-test-ntfy", 301 | data="The thttp test suite was executed!", 302 | method="POST", 303 | ) 304 | self.assertTrue(response.json["topic"] == "thttp-test-ntfy") 305 | 306 | def test_pretty_output(self): 307 | response = request("https://basehtml.xyz") 308 | 309 | f = StringIO() 310 | with contextlib.redirect_stdout(f): 311 | pretty(response) 312 | 313 | f.seek(0) 314 | output = f.read() 315 | 316 | self.assertTrue("text/html; charset=utf-8" in output) 317 | self.assertTrue("

base.html

" in output) 318 | 319 | def test_pretty_output_headers_only(self): 320 | response = request("https://basehtml.xyz") 321 | 322 | f = StringIO() 323 | with contextlib.redirect_stdout(f): 324 | pretty(response, headers_only=True) 325 | 326 | f.seek(0) 327 | output = f.read() 328 | 329 | self.assertTrue("text/html; charset=utf-8" in output) 330 | self.assertTrue("

base.html

" not in output) 331 | 332 | def test_thttp_with_mocked_response(self): 333 | mocked_response = Response(None, None, {"response": "mocked"}, 200, None, None, None) 334 | 335 | with patch("thttp.request", side_effect=[mocked_response]): 336 | response = request("https://example.org") 337 | self.assertEqual("mocked", response.json["response"]) 338 | 339 | def test_upload_single_file(self): 340 | token = os.environ.get("MEDIAPUB_TOKEN") 341 | url = os.environ.get("MEDIAPUB_URL") 342 | 343 | if not token or not url: 344 | self.skipTest("Skipping media upload test because environment variables are not available") 345 | 346 | for fn in ["test-image.png", "LICENSE.md"]: 347 | with open(fn, "rb" if fn.endswith("png") else "r") as f: 348 | response = request( 349 | url, 350 | headers={"Authorization": f"Bearer {token}"}, 351 | files={"file": f}, 352 | method="POST", 353 | ) 354 | 355 | self.assertEqual(response.status, 201) 356 | self.assertTrue("location" in response.headers) 357 | --------------------------------------------------------------------------------