Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Change: trim now is only break words is it's the only solution. + generate_seo_description() is now taking a field parameter to be easily extended.

NyanKiyoshi455aedd46884
diff --git a/requirements.in b/requirements.in
index 72084bfdde..74452ef7de 100644
--- a/requirements.in
+++ b/requirements.in
@@ -44,6 +44,7 @@ pytest-django
pytest-vcr
pytest-mock
vcrpy
+regex
requests>=1.2.0
social-auth-app-django>=2.0.0
text-unidecode
diff --git a/requirements.txt b/requirements.txt
index ceae2ec0ee..4257649f5e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -89,6 +89,7 @@ python3-openid==3.1.0 # via social-auth-core
pytz==2018.3 # via babel, celery, django
pyyaml==3.12 # via vcrpy
redis==2.10.6 # via celery, django-redis
+regex==2018.2.21
requests-oauthlib==0.8.0 # via social-auth-core
requests==2.18.4
rx==1.6.0 # via graphql-core
diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.py
index 3b7741ea08..1ced87d36f 100644
--- a/saleor/core/utils/text.py
+++ b/saleor/core/utils/text.py
@@ -1,6 +1,55 @@
+# coding: utf-8
+
import bleach
+import regex as re
+from django.forms import fields
from html5lib.serializer import HTMLSerializer
+# This will match from a cut word to a punctuation or whitespace
+LAST_WORD_SENTENCE_RE = re.compile(r'[\p{Po}\s]\w*$', re.U)
+
+
+def _get_last_word_separator_pos(text: str):
+ """Get the position of the first punctuation or whitespace next to the
+ first full word from the end of the sentence.
+
+ :param text:
+ :type text: str
+
+ :rtype: Union[int, None]
+ """
+ match = LAST_WORD_SENTENCE_RE.search(text)
+ if match:
+ # position of the last stop char
+ return match.start()
+ return None
+
+
+def trim_fullword(text: str, max_length: int):
+ """Trim text to a length lesser than `max_length` without cutting words
+ in their middle.
+
+ If it failed to trim the text (first word too long), the word will be cut.
+
+ :param text: The text to trim.
+ :type text: str
+
+ :param max_length: The maximal length of the new string to return.
+ :type max_length: int
+
+ :rtype: str
+ """
+ new_text = text[:max_length]
+
+ if len(text) > max_length:
+ # if the last char wasn't a punctuation or whitespace,
+ # try to cut in another place or if unable,
+ # just return the sentence with the word cut
+ if not _get_last_word_separator_pos(text[max_length]):
+ end_pos = _get_last_word_separator_pos(new_text)
+ new_text = new_text[:end_pos]
+ return new_text
+
def get_cleaner(**serializer_kwargs: bool):
"""
@@ -49,9 +98,9 @@ def strip_html(text: str, **serializer_kwargs: bool):
return text
-def generate_seo_description(html_text):
+def generate_seo_description(html_text: str, target_field: fields.CharField):
"""Strips HTML tags and whitespaces from text,
then trim the description."""
text = strip_html(html_text, strip_whitespace=True)
- text = text[:300]
+ text = trim_fullword(text, target_field.max_length)
return text
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index d6a51842a0..8271455fcb 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -181,7 +181,7 @@ class ProductForm(forms.ModelForm):
# generate a SEO friendly from HTML description
seo_description = generate_seo_description(
- product_description)
+ product_description, self.fields['seo_description'])
return seo_description
diff --git a/saleor/product/migrations/0053_product_seo_description.py b/saleor/product/migrations/0053_product_seo_description.py
index db718ee920..a937e604f4 100644
--- a/saleor/product/migrations/0053_product_seo_description.py
+++ b/saleor/product/migrations/0053_product_seo_description.py
@@ -6,20 +6,23 @@ from django.db import migrations, models
from saleor.core.utils.text import generate_seo_description
-def to_seo_friendly(text):
+def to_seo_friendly(cls, text):
# saleor descriptions are stored as escaped HTML,
# we need to decode them before processing them
text = html.unescape(text)
# cleanup the description and make it seo friendly
- return generate_seo_description(text)
+ return generate_seo_description(text, cls._meta.get_field(
+ 'seo_description'))
def assign_seo_descriptions(apps, schema_editor):
Product = apps.get_model('product', 'Product')
for product in Product.objects.all():
if product.seo_description is None:
- product.seo_description = to_seo_friendly(product.description)
+ product.seo_description = to_seo_friendly(
+ Product,
+ product.description)
product.save()
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index 9f9937c025..56218cbc34 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -695,10 +695,12 @@ def test_sanitize_product_description(product_type, default_category):
form.save()
assert product.description == (
'<b>bold</b><p><i>italic</i></p><h2>Header</h2><h3>subheader</h3>'
- '<blockquote>quote</blockquote><p><a href="www.mirumee.com">link</a></p>'
+ '<blockquote>quote</blockquote>'
+ '<p><a href="www.mirumee.com">link</a></p>'
'<p>an &lt;script&gt;evil()&lt;/script&gt;example</p>')
- assert product.seo_description == 'bolditalicHeadersubheaderquotelinkan evil()example'
+ assert product.seo_description == (
+ 'bolditalicHeadersubheaderquotelinkan evil()example')
def test_set_product_seo_description(unavailable_product):
@@ -715,3 +717,36 @@ def test_set_product_seo_description(unavailable_product):
assert form.is_valid()
form.save()
assert unavailable_product.seo_description == seo_description
+
+
+def test_set_product_description_too_long_for_seo(unavailable_product):
+ description = (
+ 'Saying it fourth made saw light bring beginning kind over herb '
+ 'won\'t creepeth multiply dry rule divided fish herb cattle greater '
+ 'fly divided midst, gathering can\'t moveth seed greater subdue. '
+ 'Lesser meat living fowl called. Dry don\'t wherein. Doesn\'t above '
+ 'form sixth. Image moving earth without forth light whales. Seas '
+ 'were first form fruit that form they\'re, shall air. And. Good of'
+ 'signs darkness be place. Was. Is form it. Whose. Herb signs stars '
+ 'fill own fruit wherein. '
+ 'Don\'t set man face living fifth Thing the whales were. '
+ 'You fish kind. '
+ 'Them, his under wherein place first you night gathering.')
+
+ data = model_to_dict(unavailable_product)
+ data['price'] = 20
+ data['description'] = description
+
+ form = ProductForm(data, instance=unavailable_product)
+
+ assert form.is_valid()
+ form.save()
+
+ assert len(unavailable_product.seo_description) < 300
+ assert unavailable_product.seo_description == (
+ 'Saying it fourth made saw light bring beginning kind over herb '
+ 'won\'t creepeth multiply dry rule divided fish herb cattle greater '
+ 'fly divided midst, gathering can\'t moveth seed greater subdue. '
+ 'Lesser meat living fowl called. Dry don\'t wherein. Doesn\'t above '
+ 'form sixth. Image moving earth without'
+ )
diff --git a/tests/test_core.py b/tests/test_core.py
index 5352030ab5..1e227bab33 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -8,7 +8,8 @@ from saleor.account.models import Address, User
from saleor.core.utils import (
Country, create_superuser, format_money, get_country_by_ip,
get_currency_for_country, random_data)
-from saleor.core.utils.text import strip_html, get_cleaner
+from saleor.core.utils.text import (
+ _get_last_word_separator_pos, get_cleaner, strip_html, trim_fullword)
from saleor.discount.models import Sale, Voucher
from saleor.order.models import Order
from saleor.product.models import Product
@@ -163,6 +164,22 @@ def test_manifest(client, site_settings):
assert content['description'] == site_settings.description
+def test_utils_get_last_stop_char():
+ assert _get_last_word_separator_pos('') is None
+ assert _get_last_word_separator_pos('this a cut sentenc') == 10
+ assert _get_last_word_separator_pos('.') == 0
+ assert _get_last_word_separator_pos('こんにちは。') == 5
+ assert _get_last_word_separator_pos('여보세요;세계') == 4
+
+
+def test_trim_fullword():
+ assert trim_fullword('don\'t break', 10) == 'don\'t'
+ assert trim_fullword('this is a sentence', 5) == 'this'
+ assert trim_fullword('thisIsTooLongJustCutIt', 4) == 'this'
+ assert trim_fullword('this\nis\nmultiline', 5) == 'this'
+ assert trim_fullword('', 5) == ''
+
+
def test_utils_get_cleaner_invalid_parameters():
with pytest.raises(ValueError):
get_cleaner(bad=True)