From 1a040a94f466c39b0bd2b186b329d638de25ee4e Mon Sep 17 00:00:00 2001 From: Simon Garrelou Date: Fri, 28 Aug 2020 10:22:26 +0200 Subject: [PATCH] Create Set-Cookie header before returning Response (fix #17) --- requests_mock/compat.py | 10 ++++++++++ requests_mock/response.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/requests_mock/compat.py b/requests_mock/compat.py index 8b6293a..94c50dc 100644 --- a/requests_mock/compat.py +++ b/requests_mock/compat.py @@ -28,3 +28,13 @@ def get_all(self, name, failobj=None): return [self.headers[name]] except KeyError: return failobj + + +class _FakeHTTPResponse(object): + + def __init__(self, headers): + self._headers = headers + self.msg = _FakeHTTPMessage(headers) + + def isclosed(self): + return True \ No newline at end of file diff --git a/requests_mock/response.py b/requests_mock/response.py index 3643625..cb1fd25 100644 --- a/requests_mock/response.py +++ b/requests_mock/response.py @@ -11,6 +11,7 @@ # under the License. import json as jsonutils +import urllib from requests.adapters import HTTPAdapter from requests.cookies import MockRequest, MockResponse @@ -139,6 +140,21 @@ def read(self, *args, **kwargs): return result +def create_set_cookie_header(response, jar): + """ + :param requests.packages.urllib3.response response: the Response that will be updated with the Set-Cookie header + :param requests.cookies.RequestsCookieJar jar: a CookieJar containing all cookies to be converted in a Set-Cookie header + """ + set_cookie_items = [] + for cookie_name, cookie_value in response.cookies.items(): + set_cookie_items.append(cookie_name + '=' + urllib.parse.quote(cookie_value)) + + set_cookie_header = "; ".join(set_cookie_items) + + if set_cookie_header: + response.headers["Set-Cookie"] = set_cookie_header + + def create_response(request, **kwargs): """ :param int status_code: The status code to return upon a successful @@ -206,6 +222,9 @@ def create_response(request, **kwargs): _extract_cookies(request, response, kwargs.get('cookies')) + create_set_cookie_header(response, response.cookies) + response.raw._original_response = compat._FakeHTTPResponse(response.headers) + return response