Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Last active October 13, 2018 07:50
Show Gist options
  • Save theY4Kman/81d54c28e1a2b45c4a4573855840ae5c to your computer and use it in GitHub Desktop.
Save theY4Kman/81d54c28e1a2b45c4a4573855840ae5c to your computer and use it in GitHub Desktop.
import pytest
def RecordResponse(title=None):
import pytest
class RecordResponse:
@pytest.mark.record_response(title=title)
def it_records_response(self):
pass
return RecordResponse
def print_full_request(response, request_headers=('authentication',), response_headers=()):
import json
ALLOWED_HEADERS = {
'content-type',
'www-authenticate',
}
lines = []
# Request
request = response.wsgi_request
lines.append(f'```json')
path = request.path
if request.META.get('QUERY_STRING'):
path += '?' + request.META['QUERY_STRING']
lines.append(f'{request.method} {path} HTTP/1.1')
for header in request_headers:
meta = f'HTTP_' + header.upper()
if meta in request.META:
value = request.META[meta]
lines.append(f'{header}: {value}')
data = response.renderer_context['request'].data
if data:
lines += [
f'Content-Type: {request.content_type}',
f'',
f'{json.dumps(data, indent=4)}'
]
lines.append('```')
# Response
lines.append(f'```json')
lines.append(f'HTTP/1.1 {response.status_code} {response.reason_phrase}')
lines += [': '.join((header, value))
for header, value in response.items()
if header.lower() in ALLOWED_HEADERS]
if response.content:
lines += [
'',
json.dumps(response.data, indent=4, default=lambda o: str(o)),
]
lines.append('```')
return '\n'.join(lines)
_did_print_header = False
def get_client(client, request):
global _did_print_header
if not 'record_response' in request.keywords:
return client
if not _did_print_header:
with open('./responses.txt', 'a+') as fp:
fp.write('# Example Responses\n\n')
_did_print_header = True
mark = request.keywords['record_response']
title = mark.kwargs.get('title', '\<Request\>')
old_request = client.request
def new_request(*args, **kwargs):
response = old_request(*args, **kwargs)
with open('./responses.txt', 'a+') as fp:
fp.write(f'## {title}\n')
fp.write(print_full_request(response))
fp.write('\n\n\n\n')
return response
client.request = new_request
return client
def override_client_fixture(fixture_name):
def client(request):
fixture = request.getfixturevalue(fixture_name)
return get_client(fixture, request)
client.__name__ = fixture_name
globals()[fixture_name] = pytest.fixture(client)
from tests.fixtures.api.clients import __all__ as exposed_api_fixture_names
for name in exposed_api_fixture_names:
if name.endswith('_client') and not name.startswith('make_'):
override_client_fixture(name)
override_client_fixture('unauthed_client')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment