Skip to content

Commit

Permalink
issue-7: Add templating for response body and response headers closes #7
Browse files Browse the repository at this point in the history
  • Loading branch information
lowitea committed Jan 11, 2022
1 parent 5a94f4e commit c08325c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
26 changes: 26 additions & 0 deletions http_stubs/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,32 @@ def test_proxy_httpstub_executor(
assert log.response_headers == fake_response.headers
assert log.resp_status == fake_response.status_code

def test_response_templating(self, http_stub_factory, client):
"""Tests response templating.
:param client: http client fixture
"""
tpl = 'arg1=$arg1 arg2=$arg2 $ $none body=$body'

http_stub_factory(
path='/test/',
regex_path=True,
method=HTTPMethod.POST,
resp_body=tpl,
resp_headers={'TEST': tpl},
)
response = client.post(
'/test/?arg1=Kesha&arg2=42',
'big body',
'text/plain',
)

exp_string = b'arg1=Kesha arg2=42 $ $none body=big body'

assert response.status_code == HTTPStatus.OK
assert response.content == exp_string
assert response._headers['test'][1] == exp_string.decode()


@pytest.mark.parametrize(
'body, encoding, expect', (
Expand Down
14 changes: 12 additions & 2 deletions http_stubs/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import json
from string import Template
from time import sleep
from typing import Optional, Tuple, Union
from wsgiref.util import is_hop_by_hop
Expand Down Expand Up @@ -35,13 +37,21 @@ def _httpstub_executor(
"""
sleep(stub.resp_delay / 1000)

request_body = _request_body_decode(request)

tmp_ctx = {'body': request_body}

for key, value in dict(request.GET).items():
tmp_ctx[key] = value[0]

response = HttpResponse(
content=stub.resp_body,
content=Template(stub.resp_body).safe_substitute(tmp_ctx),
content_type=stub.resp_content_type,
status=stub.resp_status,
)

for header_name, header_value in stub.resp_headers.items():
header_value = Template(header_value).safe_substitute(tmp_ctx)
response[header_name] = header_value

result_script = 'Was launched' if stub.request_script else ''
Expand All @@ -51,7 +61,7 @@ def _httpstub_executor(
method=request.method,
source_ip=request.META['REMOTE_ADDR'],
request_headers=dict(request.headers),
request_body=_request_body_decode(request),
request_body=request_body,
http_stub=stub,
result_script=result_script,
resp_status=stub.resp_status,
Expand Down

0 comments on commit c08325c

Please sign in to comment.