httprest 0.1.1__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: httprest
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: A library for making simple REST-like HTTP requests
5
5
  Home-page: https://github.com/litteratum/httprest
6
6
  License: MIT
@@ -71,3 +71,16 @@ And then you simply use it in the API client:
71
71
  api = MyAPI(..., http_client=MyHTTPClient())
72
72
  ```
73
73
 
74
+ ### Fake client
75
+ The library provides the `http.fake_client` module containing `FakeHTTPClient` class.
76
+ That class may be used for API testing. Example:
77
+ ```python
78
+ from httprest.http.fake_client import FakeHTTPClient, HTTPResponse
79
+
80
+ http_client = FakeHTTPClient(responses=[HTTPResponse(200, b"", headers={})])
81
+ api = MyAPI(..., http_client=http_client)
82
+ api.operation()
83
+ # assert your expectations here
84
+ assert http_client.history == [...]
85
+ ```
86
+
@@ -42,3 +42,16 @@ And then you simply use it in the API client:
42
42
 
43
43
  api = MyAPI(..., http_client=MyHTTPClient())
44
44
  ```
45
+
46
+ ### Fake client
47
+ The library provides the `http.fake_client` module containing `FakeHTTPClient` class.
48
+ That class may be used for API testing. Example:
49
+ ```python
50
+ from httprest.http.fake_client import FakeHTTPClient, HTTPResponse
51
+
52
+ http_client = FakeHTTPClient(responses=[HTTPResponse(200, b"", headers={})])
53
+ api = MyAPI(..., http_client=http_client)
54
+ api.operation()
55
+ # assert your expectations here
56
+ assert http_client.history == [...]
57
+ ```
@@ -4,6 +4,8 @@ from typing import Optional as _Optional
4
4
 
5
5
  from httprest.http import HTTPClient as _HTTPClient
6
6
  from httprest.http import HTTPResponse as _HTTPResponse
7
+ from httprest.http.auth import BaseAuth as _BaseAuth
8
+ from httprest.http.cert import ClientCertificate as _ClientCertificate
7
9
  from httprest.http.urllib_client import UrllibHTTPClient as _UrllibHTTPClient
8
10
 
9
11
 
@@ -31,15 +33,25 @@ class API:
31
33
  endpoint: str,
32
34
  json: _Optional[dict] = None,
33
35
  headers: _Optional[dict] = None,
36
+ params: _Optional[dict] = None,
37
+ auth: _Optional[_BaseAuth] = None,
38
+ cert: _Optional[_ClientCertificate] = None,
34
39
  ) -> _HTTPResponse:
40
+ # pylint: disable=too-many-arguments
35
41
  """Make API request.
36
42
 
37
- :param method: request HTTP method (case-insensitive)
38
43
  :param endpoint: API endpoint. Will be appended to the base URL
39
- :param json: JSON data to send in the request body
44
+
45
+ Other parameters are the same as for the `HTTPClient.request` method
40
46
  """
41
47
  return self._http_client.request(
42
- method, self._build_url(endpoint), json, headers
48
+ method=method,
49
+ url=self._build_url(endpoint),
50
+ json=json,
51
+ headers=headers,
52
+ params=params,
53
+ auth=auth,
54
+ cert=cert,
43
55
  )
44
56
 
45
57
  def _build_url(self, endpoint: str) -> str:
@@ -0,0 +1,31 @@
1
+ """HTTP auth."""
2
+
3
+ import base64
4
+ from abc import ABC, abstractmethod
5
+
6
+
7
+ class BaseAuth(ABC):
8
+ """Auth."""
9
+
10
+ def apply(self, headers: dict) -> dict:
11
+ """Apply auth headers."""
12
+ headers["Authorization"] = self._get_auth_header()
13
+ return headers
14
+
15
+ @abstractmethod
16
+ def _get_auth_header(self) -> str:
17
+ """Get auth header."""
18
+
19
+
20
+ class BasicAuth(BaseAuth):
21
+ """HTTP basic auth."""
22
+
23
+ def __init__(self, username: str, password: str) -> None:
24
+ self.username = username
25
+ self.password = password
26
+
27
+ def _get_auth_header(self) -> str:
28
+ credentials = base64.b64encode(
29
+ f"{self.username}:{self.password}".encode("utf-8")
30
+ ).decode("utf-8")
31
+ return f"Basic {credentials}"
@@ -4,6 +4,10 @@ import json as jsonlib
4
4
  import logging
5
5
  from abc import ABC, abstractmethod
6
6
  from typing import Optional
7
+ from urllib.parse import urlencode
8
+
9
+ from .auth import BaseAuth
10
+ from .cert import ClientCertificate
7
11
 
8
12
 
9
13
  class HTTPRequestError(Exception):
@@ -80,13 +84,19 @@ class HTTPClient(ABC):
80
84
  url: str,
81
85
  json: Optional[dict] = None,
82
86
  headers: Optional[dict] = None,
87
+ cert: Optional[ClientCertificate] = None,
83
88
  ) -> HTTPResponse:
89
+ # pylint: disable=too-many-arguments
84
90
  """Perform request.
85
91
 
86
92
  This method must handle all possible HTTP exceptions and raise them
87
93
  as `HTTPRequestError`.
88
94
 
89
95
  Headers may be extended if necessary.
96
+
97
+ .. warning:: there is no unified handling for `cert`. The client must
98
+ raise NotImplementedError if client side certificates are not
99
+ supported
90
100
  """
91
101
 
92
102
  def request(
@@ -95,13 +105,25 @@ class HTTPClient(ABC):
95
105
  url: str,
96
106
  json: Optional[dict] = None,
97
107
  headers: Optional[dict] = None,
108
+ params: Optional[dict] = None,
109
+ auth: Optional[BaseAuth] = None,
110
+ cert: Optional[ClientCertificate] = None,
98
111
  ) -> HTTPResponse:
112
+ # pylint: disable=too-many-arguments
99
113
  """Perform HTTP request with a given HTTP method.
100
114
 
101
115
  :param method: HTTP method to use
102
116
  :param url: API URL
103
117
  :param json: JSON data to post
104
118
  :param headers: headers
119
+ :param params: query parameters. If provided, the url will be extended
120
+ :param auth: authorization to use. If provided, the headers will be
121
+ extended
122
+ :param cert: client side certificate
105
123
  """
106
124
  logging.info("%s %s", method.upper(), url)
107
- return self._request(method, url, json, headers=headers)
125
+ if auth:
126
+ headers = auth.apply(headers or {})
127
+ if params:
128
+ url = f"{url}?{urlencode(params)}"
129
+ return self._request(method, url, json, headers=headers, cert=cert)
@@ -0,0 +1,11 @@
1
+ """Certificates."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class ClientCertificate:
7
+ """Client certificate."""
8
+
9
+ def __init__(self, cert_path: str, key_path: Optional[str] = None) -> None:
10
+ self.cert_path = cert_path
11
+ self.key_path = key_path
@@ -0,0 +1,47 @@
1
+ """Fake client."""
2
+
3
+ from typing import Any, Dict, List, Optional, Union
4
+
5
+ from httprest.http.base import HTTPResponse
6
+
7
+ from .base import HTTPClient, HTTPTimeoutError
8
+ from .cert import ClientCertificate
9
+
10
+
11
+ class FakeHTTPClient(HTTPClient):
12
+ """Fake HTTP client."""
13
+
14
+ def __init__(
15
+ self, responses: Optional[List[Union[Exception, HTTPResponse]]] = None
16
+ ) -> None:
17
+ # pylint:disable=super-init-not-called
18
+ self.history: List[Dict[str, Optional[Any]]] = []
19
+ self._responses = responses
20
+
21
+ def _request(
22
+ self,
23
+ method: str,
24
+ url: str,
25
+ json: Optional[dict] = None,
26
+ headers: Optional[dict] = None,
27
+ cert: Optional[ClientCertificate] = None,
28
+ ) -> HTTPResponse:
29
+ # pylint:disable=too-many-arguments
30
+ self.history.append(
31
+ {
32
+ "_method": "_request",
33
+ "method": method,
34
+ "url": url,
35
+ "json": json,
36
+ "headers": headers,
37
+ "cert": cert,
38
+ }
39
+ )
40
+ if not self._responses:
41
+ raise HTTPTimeoutError("No response provided")
42
+
43
+ response = self._responses.pop(0)
44
+ if isinstance(response, Exception):
45
+ raise response
46
+
47
+ return response
@@ -11,6 +11,7 @@ from .base import (
11
11
  HTTPResponse,
12
12
  HTTPTimeoutError,
13
13
  )
14
+ from .cert import ClientCertificate
14
15
 
15
16
 
16
17
  class RequestsHTTPClient(HTTPClient):
@@ -26,11 +27,26 @@ class RequestsHTTPClient(HTTPClient):
26
27
  url: str,
27
28
  json: Optional[dict] = None,
28
29
  headers: Optional[dict] = None,
30
+ cert: Optional[ClientCertificate] = None,
29
31
  ) -> HTTPResponse:
32
+ # pylint: disable=too-many-arguments
33
+ client_cert = None
34
+ if cert:
35
+ client_cert = (
36
+ cert.cert_path
37
+ if cert.key_path is None
38
+ else (cert.cert_path, cert.key_path)
39
+ )
30
40
  try:
31
41
  response: requests.Response = getattr(
32
42
  self._session, method.lower()
33
- )(url, json=json, timeout=self.request_timeout, headers=headers)
43
+ )(
44
+ url,
45
+ json=json,
46
+ timeout=self.request_timeout,
47
+ headers=headers,
48
+ cert=client_cert,
49
+ )
34
50
  except ConnectionError as exc:
35
51
  raise HTTPConnectionError(exc) from exc
36
52
  except requests.Timeout as exc:
@@ -14,6 +14,7 @@ from .base import (
14
14
  HTTPResponse,
15
15
  HTTPTimeoutError,
16
16
  )
17
+ from .cert import ClientCertificate
17
18
 
18
19
 
19
20
  class UrllibHTTPClient(HTTPClient):
@@ -26,6 +27,7 @@ class UrllibHTTPClient(HTTPClient):
26
27
  url: str,
27
28
  json: Optional[dict] = None,
28
29
  headers: Optional[dict] = None,
30
+ cert: Optional[ClientCertificate] = None,
29
31
  ) -> HTTPResponse:
30
32
  headers = headers or {}
31
33
  data = None
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "httprest"
3
- version = "0.1.1"
3
+ version = "0.1.3"
4
4
  description = "A library for making simple REST-like HTTP requests"
5
5
  authors = ["Andrii Nechaiev <andrewnech@gmail.com>"]
6
6
  readme = "README.md"
File without changes
File without changes