| 1 |
import inspect |
| 2 |
from json import dumps as json_dumps |
| 3 |
from json import loads as json_loads |
| 4 |
from typing import Any, Callable, Dict, List, Optional, Tuple, Union |
| 5 |
from unittest.mock import Mock |
| 6 |
from urllib.parse import urljoin |
| 7 |
|
| 8 |
from django.http import QueryDict, StreamingHttpResponse |
| 9 |
from django.http.request import HttpHeaders, HttpRequest |
| 10 |
|
| 11 |
from ninja import NinjaAPI, Router |
| 12 |
from ninja.responses import NinjaJSONEncoder |
| 13 |
from ninja.responses import Response as HttpResponse |
| 14 |
|
| 15 |
|
| 16 |
def build_absolute_uri(location: Optional[str] = None) -> str: |
| 17 |
base = "http://testlocation/" |
| 18 |
|
| 19 |
if location: |
| 20 |
base = urljoin(base, location) |
| 21 |
|
| 22 |
return base |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
class NinjaClientBase: |
| 28 |
__test__ = False |
| 29 |
|
| 30 |
def __init__( |
| 31 |
self, |
| 32 |
router_or_app: Union[NinjaAPI, Router], |
| 33 |
headers: Optional[Dict[str, str]] = None, |
| 34 |
COOKIES: Optional[Dict[str, str]] = None, |
| 35 |
) -> None: |
| 36 |
self.headers = headers or {} |
| 37 |
self.cookies = COOKIES or {} |
| 38 |
self.router_or_app = router_or_app |
| 39 |
|
| 40 |
def get( |
| 41 |
self, path: str, data: Optional[Dict] = None, **request_params: Any |
| 42 |
) -> "NinjaResponse": |
| 43 |
return self.request("GET", path, data, **request_params) |
| 44 |
|
| 45 |
def post( |
| 46 |
self, |
| 47 |
path: str, |
| 48 |
data: Optional[Dict] = None, |
| 49 |
json: Any = None, |
| 50 |
**request_params: Any, |
| 51 |
) -> "NinjaResponse": |
| 52 |
return self.request("POST", path, data, json, **request_params) |
| 53 |
|
| 54 |
def patch( |
| 55 |
self, |
| 56 |
path: str, |
| 57 |
data: Optional[Dict] = None, |
| 58 |
json: Any = None, |
| 59 |
**request_params: Any, |
| 60 |
) -> "NinjaResponse": |
| 61 |
return self.request("PATCH", path, data, json, **request_params) |
| 62 |
|
| 63 |
def put( |
| 64 |
self, |
| 65 |
path: str, |
| 66 |
data: Optional[Dict] = None, |
| 67 |
json: Any = None, |
| 68 |
**request_params: Any, |
| 69 |
) -> "NinjaResponse": |
| 70 |
return self.request("PUT", path, data, json, **request_params) |
| 71 |
|
| 72 |
def delete( |
| 73 |
self, |
| 74 |
path: str, |
| 75 |
data: Optional[Dict] = None, |
| 76 |
json: Any = None, |
| 77 |
**request_params: Any, |
| 78 |
) -> "NinjaResponse": |
| 79 |
return self.request("DELETE", path, data, json, **request_params) |
| 80 |
|
| 81 |
def request( |
| 82 |
self, |
| 83 |
method: str, |
| 84 |
path: str, |
| 85 |
data: Optional[Dict] = None, |
| 86 |
json: Any = None, |
| 87 |
**request_params: Any, |
| 88 |
) -> "NinjaResponse": |
| 89 |
if json is not None: |
| 90 |
request_params["body"] = json_dumps(json, cls=NinjaJSONEncoder) |
| 91 |
if data is None: |
| 92 |
data = {} |
| 93 |
if self.headers or request_params.get("headers"): |
| 94 |
request_params["headers"] = { |
| 95 |
**self.headers, |
| 96 |
**request_params.get("headers", {}), |
| 97 |
} |
| 98 |
if self.cookies or request_params.get("COOKIES"): |
| 99 |
request_params["COOKIES"] = { |
| 100 |
**self.cookies, |
| 101 |
**request_params.get("COOKIES", {}), |
| 102 |
} |
| 103 |
func, request, kwargs = self._resolve(method, path, data, request_params) |
| 104 |
return self._call(func, request, kwargs) |
| 105 |
|
| 106 |
@property |
| 107 |
def urls(self) -> List: |
| 108 |
if not hasattr(self, "_urls_cache"): |
| 109 |
self._urls_cache: List |
| 110 |
if isinstance(self.router_or_app, NinjaAPI): |
| 111 |
self._urls_cache = self.router_or_app.urls[0] |
| 112 |
else: |
| 113 |
|
| 114 |
|
| 115 |
api = NinjaAPI(urls_namespace=f"test-{id(self)}") |
| 116 |
api.add_router("", self.router_or_app) |
| 117 |
self._urls_cache = api.urls[0] |
| 118 |
return self._urls_cache |
| 119 |
|
| 120 |
def _resolve( |
| 121 |
self, method: str, path: str, data: Dict, request_params: Any |
| 122 |
) -> Tuple[Callable, Mock, Dict]: |
| 123 |
url_path = path.split("?")[0].lstrip("/") |
| 124 |
for url in self.urls: |
| 125 |
match = url.resolve(url_path) |
| 126 |
if match: |
| 127 |
request = self._build_request(method, path, data, request_params) |
| 128 |
return match.func, request, match.kwargs |
| 129 |
raise Exception(f'Cannot resolve "{path}"') |
| 130 |
|
| 131 |
def _build_request( |
| 132 |
self, method: str, path: str, data: Dict, request_params: Any |
| 133 |
) -> Mock: |
| 134 |
request = Mock(spec=HttpRequest) |
| 135 |
request.method = method |
| 136 |
request.path = path |
| 137 |
request.body = "" |
| 138 |
request.COOKIES = {} |
| 139 |
request._dont_enforce_csrf_checks = True |
| 140 |
request.is_secure.return_value = False |
| 141 |
request.build_absolute_uri = build_absolute_uri |
| 142 |
|
| 143 |
request.auth = None |
| 144 |
request.user = Mock() |
| 145 |
if "user" not in request_params: |
| 146 |
request.user.is_authenticated = False |
| 147 |
request.user.is_staff = False |
| 148 |
request.user.is_superuser = False |
| 149 |
|
| 150 |
request.META = request_params.pop("META", {"REMOTE_ADDR": "127.0.0.1"}) |
| 151 |
request.FILES = request_params.pop("FILES", {}) |
| 152 |
|
| 153 |
request.META.update({ |
| 154 |
f"HTTP_{k.replace('-', '_')}": v |
| 155 |
for k, v in request_params.pop("headers", {}).items() |
| 156 |
}) |
| 157 |
|
| 158 |
request.headers = HttpHeaders(request.META) |
| 159 |
|
| 160 |
if isinstance(data, QueryDict): |
| 161 |
request.POST = data |
| 162 |
else: |
| 163 |
request.POST = QueryDict(mutable=True) |
| 164 |
|
| 165 |
if isinstance(data, (str, bytes)): |
| 166 |
request_params["body"] = data |
| 167 |
elif data: |
| 168 |
for k, v in data.items(): |
| 169 |
request.POST[k] = v |
| 170 |
|
| 171 |
if "?" in path: |
| 172 |
request.GET = QueryDict(path.split("?")[1]) |
| 173 |
else: |
| 174 |
query_params = request_params.pop("query_params", None) |
| 175 |
if query_params: |
| 176 |
query_dict = QueryDict(mutable=True) |
| 177 |
for k, v in query_params.items(): |
| 178 |
if isinstance(v, list): |
| 179 |
for item in v: |
| 180 |
query_dict.appendlist(k, item) |
| 181 |
else: |
| 182 |
query_dict[k] = v |
| 183 |
request.GET = query_dict |
| 184 |
else: |
| 185 |
request.GET = QueryDict() |
| 186 |
|
| 187 |
for k, v in request_params.items(): |
| 188 |
setattr(request, k, v) |
| 189 |
return request |
| 190 |
|
| 191 |
|
| 192 |
class TestClient(NinjaClientBase): |
| 193 |
def _call(self, func: Callable, request: Mock, kwargs: Dict) -> "NinjaResponse": |
| 194 |
return NinjaResponse(func(request, **kwargs)) |
| 195 |
|
| 196 |
|
| 197 |
class TestAsyncClient(NinjaClientBase): |
| 198 |
async def _call( |
| 199 |
self, func: Callable, request: Mock, kwargs: Dict |
| 200 |
) -> "NinjaResponse": |
| 201 |
http_response = await func(request, **kwargs) |
| 202 |
if http_response.streaming and inspect.isasyncgen( |
| 203 |
http_response.streaming_content |
| 204 |
): |
| 205 |
|
| 206 |
chunks = [] |
| 207 |
async for chunk in http_response.streaming_content: |
| 208 |
chunks.append( |
| 209 |
chunk.encode("utf-8") if isinstance(chunk, str) else chunk |
| 210 |
) |
| 211 |
|
| 212 |
http_response.streaming_content = iter(chunks) |
| 213 |
return NinjaResponse(http_response) |
| 214 |
|
| 215 |
|
| 216 |
class NinjaResponse: |
| 217 |
def __init__(self, http_response: Union[HttpResponse, StreamingHttpResponse]): |
| 218 |
self._response = http_response |
| 219 |
self.status_code = http_response.status_code |
| 220 |
self.streaming = http_response.streaming |
| 221 |
if self.streaming: |
| 222 |
assert isinstance(http_response, StreamingHttpResponse) |
| 223 |
self.content = b"".join( |
| 224 |
chunk.encode("utf-8") if isinstance(chunk, str) else chunk |
| 225 |
for chunk in http_response.streaming_content |
| 226 |
) |
| 227 |
else: |
| 228 |
self.content = http_response.content |
| 229 |
self._data = None |
| 230 |
|
| 231 |
def json(self) -> Any: |
| 232 |
return json_loads(self.content) |
| 233 |
|
| 234 |
@property |
| 235 |
def data(self) -> Any: |
| 236 |
if self._data is None: |
| 237 |
self._data = self.json() |
| 238 |
return self._data |
| 239 |
|
| 240 |
def __getitem__(self, key: str) -> Any: |
| 241 |
return self._response[key] |
| 242 |
|
| 243 |
def __getattr__(self, attr: str) -> Any: |
| 244 |
return getattr(self._response, attr) |