Skip to content

Commit

Permalink
Inlines tests; change feature.get_url and feature.get_full_url to cla…
Browse files Browse the repository at this point in the history
…ssmethod
  • Loading branch information
Nigel2392 committed Mar 26, 2024
1 parent 69eaf7f commit bd50ce7
Show file tree
Hide file tree
Showing 8 changed files with 243 additions and 46 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = wagtail_editorjs
version = 1.3.6
version = 1.3.7
description = EditorJS as a widget for Wagtail, with Page- and Image chooser support
long_description = file: README.md
long_description_content_type = text/markdown
Expand Down
82 changes: 55 additions & 27 deletions wagtail_editorjs/editorjs/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,24 @@ class LinkFeature(ModelInlineEditorJSFeature):
chooser_class = AdminPageChooser
model = Page

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.must_have_attrs = self.must_have_attrs | {
"data-parent-id": None,
"href": None,
}
@classmethod
def get_url(cls, instance):
return instance.get_url()

@classmethod
def get_full_url(cls, instance, request):
return instance.get_full_url(request)

@classmethod
def get_test_queryset(cls):
return super().get_test_queryset().filter(depth__gt=1)

# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.must_have_attrs = self.must_have_attrs | {
# "data-parent-id": None,
# "href": None,
# }


class DocumentFeature(ModelInlineEditorJSFeature):
Expand All @@ -317,6 +329,10 @@ class DocumentFeature(ModelInlineEditorJSFeature):
chooser_class = AdminDocumentChooser
model = Document

@classmethod
def get_url(cls, instance):
return instance.file.url


class ImageFeature(EditorJSFeature):
allowed_tags = ["img", "figure", "figcaption"]
Expand Down Expand Up @@ -406,7 +422,6 @@ def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSEle

return EditorJSElement(
"img",
block["data"].get("caption"),
close_tag=False,
attrs={
"src": url,
Expand All @@ -417,26 +432,26 @@ def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSEle

@classmethod
def get_test_data(cls):
# instance = Image.objects.first()
instance = Image.objects.first()
return [
# {
# "imageId": instance.pk,
# "withBorder": True,
# "stretched": False,
# "backgroundColor": "#000000",
# "usingCaption": False,
# "alt": "Image",
# "caption": "Image",
# },
# {
# "imageId": instance.pk,
# "withBorder": False,
# "stretched": True,
# "backgroundColor": None,
# "usingCaption": True,
# "alt": "Image",
# "caption": "Image",
# }
{
"imageId": instance.pk,
"withBorder": True,
"stretched": False,
"backgroundColor": "#000000",
"usingCaption": False,
"alt": "Image",
"caption": "Image",
},
{
"imageId": instance.pk,
"withBorder": False,
"stretched": True,
"backgroundColor": None,
"usingCaption": True,
"alt": "Image",
"caption": "Image",
}
]


Expand Down Expand Up @@ -527,7 +542,20 @@ def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSEle

@classmethod
def get_test_data(cls):
return []
images = Image.objects.all()[0:3]
return [
{
"images": [
{
"id": image.pk,
"title": image.title,
} for image in images
],
"settings": {
"stretched": True,
},
}
]

class TableFeature(EditorJSFeature):
allowed_tags = ["table", "tr", "th", "td", "thead", "tbody", "tfoot"]
Expand Down
46 changes: 34 additions & 12 deletions wagtail_editorjs/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,7 @@ def get_test_data(cls):
return None


class BaseInlineEditorJSFeature(BaseEditorJSFeature):
pass


class InlineEditorJSFeature(BaseInlineEditorJSFeature):
class InlineEditorJSFeature(BaseEditorJSFeature):
def __init__(self,
tool_name: str,
klass: str,
Expand Down Expand Up @@ -287,7 +283,7 @@ def filter(self, item):

return True

def parse_inline_data(self, soup: bs4.BeautifulSoup, context = None) -> tuple[bs4.BeautifulSoup, EditorJSElement, dict[Any, dict[str, Any]], Any]:
def parse_inline_data(self, soup: bs4.BeautifulSoup, context = None):
"""
Finds inline elements by the must_have_attrs and can_have_attrs.
Designed to be database-efficient; allowing for gathering of all data before
Expand Down Expand Up @@ -318,6 +314,20 @@ def parse_inline_data(self, soup: bs4.BeautifulSoup, context = None) -> tuple[bs
# Build all inlines.
self.build_elements(list(matches.items()), context=context)

@classmethod
def get_test_data(cls) -> list[tuple[str, str]]:
"""
Returns a list of test data.
The test data should be a list of tuples.
The first item in the tuple is the raw HTML tag.
The second item is the expected output.
The raw HTML tag(s) will be randomly appended into a soup.
We will use assertQueries(1) to ensure any database queries are kept to a minimum.
"""
return []

class ModelInlineEditorJSFeature(InlineEditorJSFeature):
model = None
Expand Down Expand Up @@ -379,11 +389,13 @@ def build_element(self, item, obj, context: dict[str, Any] = None):
item["class"] = f"{self.model._meta.model_name}-link"


def get_url(self, instance):
@classmethod
def get_url(cls, instance):
return instance.url

def get_full_url(self, instance, request):
return request.build_absolute_uri(self.get_url(instance))
@classmethod
def get_full_url(cls, instance, request):
return request.build_absolute_uri(cls.get_url(instance))


def build_elements(self, inline_data: list, context: dict[str, Any] = None) -> list:
Expand Down Expand Up @@ -425,9 +437,19 @@ def get_js(self):
return (self.widget.media._js or []) + super().get_js()

@classmethod
def get_test_data(cls):
return None
def get_test_queryset(cls):
return cls.model.objects.all()

@classmethod
def get_test_data(cls):
models = cls.get_test_queryset()[0:5]
return [
(
f"<a data-id='{model.id}' data-{cls.model._meta.model_name}='True' class='wagtail-{cls.model._meta.model_name}-link'></a>",
f"<a href='{cls.get_url(model)}' class='{cls.model._meta.model_name}-link'></a>"
)
for model in models
]



Expand Down Expand Up @@ -477,7 +499,7 @@ def _look_for_features(self):

def register(self, tool_name: str, feature: EditorJSFeature):
self.features[tool_name] = feature
if isinstance(feature, BaseInlineEditorJSFeature):
if isinstance(feature, InlineEditorJSFeature):
self.inline_features.append(feature)


Expand Down
4 changes: 2 additions & 2 deletions wagtail_editorjs/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from . import settings
from .registry import (
EditorJSElement,
BaseInlineEditorJSFeature,
InlineEditorJSFeature,
InlineEditorJSFeature,
EDITOR_JS_FEATURES,
)
Expand Down Expand Up @@ -42,7 +42,7 @@ def render_editorjs_html(
inlines = [
feature
for feature in feature_mappings.values()
if isinstance(feature, BaseInlineEditorJSFeature)
if isinstance(feature, InlineEditorJSFeature)
]

html = []
Expand Down
3 changes: 2 additions & 1 deletion wagtail_editorjs/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from .render import *
from .attrs import *
from .attrs import *
from .inlines import *
77 changes: 77 additions & 0 deletions wagtail_editorjs/tests/inlines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from django.test import TestCase


from .utils import BaseEditorJSTest
from ..registry import (
InlineEditorJSFeature,
EDITOR_JS_FEATURES,
)

import bs4



TESTING_HTML = """
<div class="editorjs">
<div class="editorjs-block" data-type="paragraph">
<p>Hello, World!</p>
</div>
<div class="editorjs-block" data-type="header">
<h1>Header</h1>
</div>
<div class="editorjs-block" data-type="list" data-testing-id="TARGET">
</div>
<div class="editorjs-block" data-type="table">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
</div>
</div>
"""


class TestEditorJSInline(BaseEditorJSTest):
def setUp(self):
super().setUp()
self.inlines = [
feature
for feature in EDITOR_JS_FEATURES.features.values()
if isinstance(feature, InlineEditorJSFeature)
]

def test_inlines(self):

for feature in self.inlines:
feature: InlineEditorJSFeature
test_data = feature.get_test_data()

if not test_data:
continue

soup = bs4.BeautifulSoup(TESTING_HTML, "html.parser")
testing_block = soup.find("div", {"data-testing-id": "TARGET"})
testing_block.clear()

for i, (initial, _) in enumerate(test_data):
initial_soup = bs4.BeautifulSoup(initial, "html.parser")
initial_soup.attrs["data-testing-id"] = f"test_{i}"
testing_block.append(initial_soup)

feature.parse_inline_data(soup)

html = str(soup)

outputs = [i[1] for i in test_data]
for i, output in enumerate(outputs):
self.assertInHTML(
output,
html
)
12 changes: 9 additions & 3 deletions wagtail_editorjs/tests/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
from django.utils.safestring import mark_safe
from bs4 import BeautifulSoup

from .utils import BaseEditorJSTest
from ..editorjs.element import EditorJSElement
from ..render import render_editorjs_html
from ..registry import (
EditorJSTune,
EditorJSFeature,
InlineEditorJSFeature,
EDITOR_JS_FEATURES,
)

Expand All @@ -23,9 +26,10 @@ def tune_element(self, element: EditorJSElement, tune_value: Any, context=None)


# Create your tests here.
class TestEditorJSFeatures(TestCase):
class TestEditorJSFeatures(BaseEditorJSTest):

def setUp(self) -> None:
super().setUp()
self.tune = TestEditorJSTune(
"test_tune_feature",
None
Expand All @@ -41,7 +45,8 @@ def test_editorjs_features(self):
test_data = []
for i, feature in enumerate(EDITOR_JS_FEATURES.features.values()):
test_data_list = feature.get_test_data()
if test_data_list is None:
if not isinstance(feature, (EditorJSFeature))\
or not test_data_list:
continue

for j, data in enumerate(test_data_list):
Expand Down Expand Up @@ -84,7 +89,8 @@ def test_cleaned_editorjs_features(self):
test_data = []
for i, feature in enumerate(EDITOR_JS_FEATURES.features.values()):
test_data_list = feature.get_test_data()
if test_data_list is None:
if not isinstance(feature, (EditorJSFeature))\
or not test_data_list:
continue

for j, data in enumerate(test_data_list):
Expand Down
Loading

0 comments on commit bd50ce7

Please sign in to comment.