Skip to content

Commit

Permalink
Create Set-Cookie header before returning Response
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Garrelou authored and jaraco committed Nov 30, 2022
1 parent c19c334 commit 1a040a9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
10 changes: 10 additions & 0 deletions requests_mock/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
19 changes: 19 additions & 0 deletions requests_mock/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# under the License.

import json as jsonutils
import urllib

from requests.adapters import HTTPAdapter
from requests.cookies import MockRequest, MockResponse
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down

0 comments on commit 1a040a9

Please sign in to comment.