Commit a76318ea by Renzo Lucioni

Merge pull request #272 from edx/renzo/paypal-truncation

Truncate product titles used when creating PayPal payments
parents 167710dc c0060fa7
......@@ -12,6 +12,8 @@ import paypalrestsdk
from ecommerce.extensions.order.constants import PaymentEventTypeName
from ecommerce.extensions.payment.processors import BasePaymentProcessor
from ecommerce.extensions.payment.models import PaypalWebProfile
from ecommerce.extensions.payment.utils import middle_truncate
logger = logging.getLogger(__name__)
......@@ -84,7 +86,8 @@ class Paypal(BasePaymentProcessor):
'items': [
{
'quantity': line.quantity,
'name': line.product.title,
# PayPal requires that item names be at most 127 characters long.
'name': middle_truncate(line.product.title, 127),
'price': unicode(line.price_incl_tax),
'currency': line.stockrecord.price_currency,
}
......
from django.test import TestCase
from ecommerce.extensions.payment.utils import middle_truncate
class UtilsTests(TestCase):
def test_truncation(self):
"""Verify that the truncation utility behaves as expected."""
length = 10
string = 'x' * length
# Verify that the original string is returned when no truncation is necessary.
self.assertEqual(string, middle_truncate(string, length))
self.assertEqual(string, middle_truncate(string, length + 1))
# Verify that truncation occurs when expected.
self.assertEqual('xxx...xxx', middle_truncate(string, length - 1))
self.assertEqual('xx...xx', middle_truncate(string, length - 2))
self.assertRaises(ValueError, middle_truncate, string, 0)
from django.utils.translation import ugettext_lazy as _
def middle_truncate(string, chars):
"""Truncate the provided string, if necessary.
Cuts excess characters from the middle of the string and replaces
them with a string indicating that truncation has occurred.
Arguments:
string (unicode or str): The string to be truncated.
chars (int): The character limit for the truncated string.
Returns:
Unicode: The truncated string, of length less than or equal to `chars`.
If no truncation was required, the original string is returned.
Raises:
ValueError: If the provided character limit is less than the length of
the truncation indicator.
"""
if len(string) <= chars:
return string
# Translators: This is a string placed in the middle of a truncated string
# to indicate that truncation has occurred. For example, if a title may only
# be at most 11 characters long, "A Very Long Title" (17 characters) would be
# truncated to "A Ve...itle".
indicator = _('...')
indicator_length = len(indicator)
if chars < indicator_length:
raise ValueError
slice_size = (chars - indicator_length) / 2
start, end = string[:slice_size], string[-slice_size:]
truncated = u'{start}{indicator}{end}'.format(start=start, indicator=indicator, end=end)
return truncated
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment