Skip to content
This repository has been archived by the owner on May 26, 2021. It is now read-only.

issue-77: Fix absolute request url in HttpStubAdmin with regex(#77) #78

Merged
merged 30 commits into from
Dec 13, 2020
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
495c7e9
added absolute templatetag
PetrS12 Oct 11, 2020
38225e4
added request url to stub edit page
PetrS12 Oct 11, 2020
8779577
added str_to_list filter for template
PetrS12 Oct 11, 2020
11d0672
headers in column
PetrS12 Oct 11, 2020
b061787
Merge pull request #3 from Uma-Tech/develop
PetrS12 Oct 17, 2020
b79e1a3
Merge branch 'develop' into #17-display_header_in_column
PetrS12 Oct 17, 2020
629041a
linted and added test for filter
PetrS12 Oct 17, 2020
f91a730
added change_form_template for every Admin and refactor templates
PetrS12 Nov 1, 2020
ddc7213
added change_form_template attribute
PetrS12 Nov 4, 2020
5be013d
changed local host in .sh for dev
PetrS12 Nov 4, 2020
867ae5e
str_to_list renamed to headers_to_list
PetrS12 Nov 4, 2020
4d8413c
Merge branch 'develop' of https://github.com/Uma-Tech/parrot into dev…
PetrS12 Nov 22, 2020
1ad82e3
Merge branch 'develop' into #17-display_header_in_column
PetrS12 Nov 22, 2020
27bfe76
tranclate to copied
PetrS12 Nov 22, 2020
5427684
corrected start-django.dev
PetrS12 Nov 22, 2020
4a9c169
refactored headers_to_list: added json.loads
PetrS12 Nov 28, 2020
61ab187
fixed tests and linted
PetrS12 Nov 28, 2020
184b24c
added test for ivalid headers
PetrS12 Nov 28, 2020
ab1aeae
corrected test
PetrS12 Nov 28, 2020
832fa68
Merge branch 'develop' of https://github.com/Uma-Tech/parrot into dev…
PetrS12 Dec 2, 2020
3f50a7a
fixed absolute url for stub admin page
PetrS12 Dec 2, 2020
2ab94a7
corrected name of function and doctring
PetrS12 Dec 5, 2020
c31ea9c
linted
PetrS12 Dec 5, 2020
ff604a9
renamed get_absolute_url to absolute_url
PetrS12 Dec 5, 2020
ca1945b
Merge branch 'develop' of https://github.com/Uma-Tech/parrot into dev…
PetrS12 Dec 5, 2020
9d21fa5
Merge branch 'develop' into issue-77
PetrS12 Dec 5, 2020
e0bd386
Merge branch 'develop' of https://github.com/Uma-Tech/parrot into dev…
PetrS12 Dec 13, 2020
1af158d
Merge branch 'develop' of https://github.com/Uma-Tech/parrot into dev…
PetrS12 Dec 13, 2020
71b07f7
Merge branch 'develop' into issue-77
PetrS12 Dec 13, 2020
cbc8aee
linted
PetrS12 Dec 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions http_stubs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def has_add_permission(self, *args, **kwargs) -> bool:
class HTTPStubAdmin(admin.ModelAdmin):
"""HTTP stub admin."""

change_form_template = 'admin/http_stubs/httpstub/change_form.html'
extra_buttons_style = 'background-color:#00b0ff;color:white'

actions = ['enable_action', 'disable_action']
Expand Down
42 changes: 39 additions & 3 deletions http_stubs/templatetags/stub_tags.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,54 @@
from typing import Dict
import json
from html import unescape
from json import JSONDecodeError
from typing import AnyStr, Dict, List
from urllib.parse import urlunparse

from django import template
from django.contrib.admin.helpers import Fieldset
from django.template.defaultfilters import stringfilter

Url = str

register = template.Library()


@register.simple_tag(takes_context=True, name='absolute')
def get_absolute_url_tag(context: Dict, url: Url) -> Url:
def absolute_url(context: Dict, url: Url, fieldset: Fieldset) -> Url:
"""Tag that returns an absolute url.

:param context: context of request
:param url: relative url
:param fieldset: Fieldset that is used to get value of the 'regex_path'
field from the form
:returns: absolute url
"""
return context.get('request').build_absolute_uri(url)
request = context['request']
form = fieldset.form
if form.initial.get('regex_path'):
return urlunparse(
[request.scheme, request.get_host(), '', '', '', ''],
)
if not url.startswith('/'):
url = f'/{url}'
return request.build_absolute_uri(url)


@register.filter()
@stringfilter
def headers_to_list(headers: AnyStr) -> List:
"""Filter that creates a list from a string of headers(dict).

Return a list of the lines in the string representation of the request
headers.
:param headers: string representation of the request headers
:returns: list of individual headers string representation
"""
try:
headers = json.loads(unescape(headers).replace("'", '"'))
except (TypeError, JSONDecodeError):
return []
return [
f'{header}: {header_value}'
for header, header_value in headers.items()
]
57 changes: 55 additions & 2 deletions http_stubs/tests/test_tags.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
from django.contrib.admin.helpers import Fieldset
from django.contrib.admin.sites import AdminSite
from django.http.request import HttpRequest

from http_stubs.templatetags.stub_tags import get_absolute_url_tag
from http_stubs.admin import HTTPStubAdmin
from http_stubs.models import HTTPStub
from http_stubs.templatetags import stub_tags


class TestStubTags:
"""Tests for custom tags and filters for Django templates."""

def test_absolute_url_tag_with_regex(self):
"""Check that the absolute url is correct if regex_path is true."""
req = HttpRequest()
req.META = {
'SERVER_NAME': '127.0.0.1',
'SERVER_PORT': '80',
}
relative_url = '/check/'
form = HTTPStubAdmin(
HTTPStub, AdminSite,
).get_form(req)(initial={'regex_path': True})
fieldset = Fieldset(form)
url = stub_tags.absolute_url({'request': req}, relative_url, fieldset)
assert url == 'http://127.0.0.1'

def test_absolute_url_tag(self):
"""Check that the absolute url is returned."""
req = HttpRequest()
Expand All @@ -14,5 +33,39 @@ def test_absolute_url_tag(self):
'SERVER_PORT': '80',
}
relative_url = '/check/'
url = get_absolute_url_tag({'request': req}, relative_url)
form = HTTPStubAdmin(
HTTPStub, AdminSite,
).get_form(req)(initial={'regex_path': False})
fieldset = Fieldset(form)
url = stub_tags.absolute_url({'request': req}, relative_url, fieldset)
assert url == 'http://127.0.0.1/check/'

def test_absolute_url_tag_without_slash(self):
"""Check that the absolute url is correct.

When relative url doesn`t start with a slash.
"""
req = HttpRequest()
req.META = {
'SERVER_NAME': '127.0.0.1',
'SERVER_PORT': '80',
}
relative_url = 'check'
form = HTTPStubAdmin(
HTTPStub, AdminSite,
).get_form(req)(initial={'regex_path': False})
fieldset = Fieldset(form)
url = stub_tags.absolute_url({'request': req}, relative_url, fieldset)
assert url == 'http://127.0.0.1/check'

def test_headers_to_list_filter(self):
"""Check that the list of headers is returned."""
headers = '{"Content-Length": "2", "Accept": "text/html"}'
headers_list = stub_tags.headers_to_list(headers)
assert headers_list == ['Content-Length: 2', 'Accept: text/html']

def test_headers_to_list_filter_invalid(self):
"""Check that the list of headers is empty."""
headers = 'invalid headers format'
headers_list = stub_tags.headers_to_list(headers)
assert not headers_list
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% extends "admin/change_form.html" %}
{% block field_sets %}
{% for fieldset in adminform %}
{% include "admin/http_stubs/includes/fieldset.html" %}
{% include "admin/http_stubs/includes/fieldset_http_stub.html" %}
{% endfor %}
{% endblock %}
38 changes: 11 additions & 27 deletions templates/admin/http_stubs/includes/fieldset.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% load stub_tags %}
<fieldset class="module aligned {{ fieldset.classes }}">
<legend></legend>
<legend></legend>
{% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
{% if fieldset.description %}
<div class="description">{{ fieldset.description|safe }}</div>
Expand All @@ -16,11 +16,13 @@
{% else %}
{{ field.label_tag }}
{% if field.is_readonly %}
<div class="readonly">{{ field.contents }}</div>
{% block readonly_field %}
<div class="readonly">{{ field.contents }}</div>
{% endblock %}
{% else %}
{{ field.field }}
{# added request url for path field(issue #35) #}
{% if field.field.name == 'path' %}<div class="readonly"><div id="full-path">{% absolute field.field.value %}</div><div id="path-copied-alert">Copied!</div></div>{% endif %}
{% block writable_field %}
{{ field.field }}
{% endblock %}
{% endif %}
{% endif %}
{% if field.field.help_text %}
Expand Down Expand Up @@ -193,32 +195,14 @@
}
}
ImagePreview.init({id:$("#imgBox img")});


// copy content to clipboard
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}

// copy full request path to clipboard
$("#full-path").on("click", function() {
copyToClipboard("#full-path");
$("#path-copied-alert").fadeIn("slow");
});
</script>

{% block javascripts %}
{% endblock %}

<style type="text/css">
#imgs img {
width: 24%;
}
#path-copied-alert {
display: none;
color: green;
padding-left: 170px;
}
</style>
{% block css %}
{% endblock %}
40 changes: 40 additions & 0 deletions templates/admin/http_stubs/includes/fieldset_http_stub.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{% extends 'admin/http_stubs/includes/fieldset.html' %}
{% load stub_tags %}
{% block writable_field %}
{{ field.field }}
{# added request url for path field(issue #35) #}
{% if field.field.name == 'path' %}
<div class="readonly">
<div id="full-path">{% absolute field.field.value fieldset %}</div>
<div id="path-copied-alert">Copied!</div>
</div>
{% endif %}
{% endblock %}
{% block javascripts %}
<script type="text/javascript">
// copy content to clipboard
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}

// copy full request path to clipboard
$("#full-path").on("click", function() {
copyToClipboard("#full-path");
$("#path-copied-alert").fadeIn("slow");
});

</script>
{% endblock %}
{% block css %}
<style type="text/css">
#path-copied-alert {
display: none;
color: green;
padding-left: 170px;
}
</style>
{% endblock %}
11 changes: 11 additions & 0 deletions templates/admin/http_stubs/includes/fieldset_log_entry.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends 'admin/http_stubs/includes/fieldset.html' %}
{% load stub_tags %}
{% block readonly_field %}
{% if field.field.name == 'headers' %}
<ul class="readonly">
{% for header in field.contents|headers_to_list %}
<li>{{ header }}</li>
{% endfor %}</ul>
{% else %}
<div class="readonly">{{ field.contents }}</div>{% endif %}
{% endblock %}
6 changes: 6 additions & 0 deletions templates/admin/http_stubs/logentry/change_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% extends "admin/change_form.html" %}
{% block field_sets %}
{% for fieldset in adminform %}
{% include "admin/http_stubs/includes/fieldset_log_entry.html" %}
{% endfor %}
{% endblock %}