def attach_translations(self, obj, data, source_name, target_name=None):
        """
        Look for the translation of `source_name` in `data` and create a dict
        with all translations for this field (which will look like
        {'en-US': 'mytranslation'}) and attach it to a property on `obj`.
        The property name is built with `target_name` and `cls.suffix`. If
        `target_name` is None, `source_name` is used instead.

        The suffix is necessary for two reasons:
        1) The translations app won't let us set the dict on the real field
           without making db queries
        2) This also exactly matches how we store translations in ES, so we can
           directly fetch the translations in the data passed to this method.
        """
        if target_name is None:
            target_name = source_name
        target_key = '%s%s' % (target_name, self.suffix)
        source_key = '%s%s' % (source_name, self.suffix)
        target_translations = {
            v.get('lang', ''): v.get('string', '')
            for v in data.get(source_key, {}) or {}
        }
        setattr(obj, target_key, target_translations)

        # Serializer might need the single translation in the current language,
        # so fetch it and attach it directly under `target_name`. We need a
        # fake Translation() instance to prevent SQL queries from being
        # automatically made by the translations app.
        translation = self.fetch_single_translation(obj, target_name,
                                                    target_translations,
                                                    get_language())
        if translation:
            locale, value = list(translation.items())[0]
            translation = Translation(localized_string=value, locale=locale)
        setattr(obj, target_name, translation)
Beispiel #2
0
def get_trans(items):
    if not items:
        return

    first_item = items[0]
    model = first_item.__class__
    assert hasattr(model._meta, 'translated_fields')
    deferred_fields = first_item.get_deferred_fields()
    fields = [
        field for field in model._meta.translated_fields
        if field.attname not in deferred_fields
    ]
    if not fields:
        return
    # FIXME: if we knew which db the queryset we are transforming used, we
    # could make sure we are re-using the same one.
    dbname = router.db_for_read(model)
    connection = connections[dbname]
    sql, params = _build_query(model=model,
                               connection=connection,
                               fields=fields)
    item_dict = {item.pk: item for item in items}
    ids = ','.join(map(str, item_dict.keys()))

    with connection.cursor() as cursor:
        cursor.execute(sql.format(ids='(%s)' % ids), tuple(params))
        step = len(trans_fields)
        for row in cursor.fetchall():
            # We put the item's pk as the first selected field.
            item = item_dict[row[0]]
            for index, field in enumerate(fields):
                start = 1 + step * index
                t = Translation(*row[start:start + step])
                if t.id is not None and t.localized_string is not None:
                    setattr(item, field.name, t)
Beispiel #3
0
    def setUp(self):
        super(TestCategoriesFeed, self).setUp()
        self.feed = feeds.CategoriesRss()
        self.u = u'Ελληνικά'
        self.wut = Translation(localized_string=self.u, locale='el')

        self.feed.request = mock.Mock()
        self.feed.request.APP.pretty = self.u

        self.category = Category(db_name=self.u)

        self.addon = Addon(name=self.u, id=2, type=1, slug='xx')
        self.addon._current_version = Version(version='v%s' % self.u)
    def setUp(self):
        super(FeedTest, self).setUp()
        self.feed = feeds.ReviewsRss()
        self.u = u'Ελληνικά'
        self.wut = Translation(localized_string=self.u, locale='el')

        self.addon = mock.Mock()
        self.addon.name = self.wut

        self.user = mock.Mock()
        self.user.name = self.u

        self.review = mock.Mock()
        self.review.title = self.wut
        self.review.rating = 4
        self.review.user = self.user
def get_trans(items):
    if not items:
        return

    model = items[0].__class__
    # FIXME: if we knew which db the queryset we are transforming used, we
    # could make sure we are re-using the same one.
    dbname = router.db_for_read(model)
    connection = connections[dbname]
    sql, params = build_query(model, connection)
    item_dict = dict((item.pk, item) for item in items)
    ids = ','.join(map(str, item_dict.keys()))

    cursor = connection.cursor()
    cursor.execute(sql.format(ids='(%s)' % ids), tuple(params))
    step = len(trans_fields)
    for row in cursor.fetchall():
        # We put the item's pk as the first selected field.
        item = item_dict[row[0]]
        for index, field in enumerate(model._meta.translated_fields):
            start = 1 + step * index
            t = Translation(*row[start:start + step])
            if t.id is not None and t.localized_string is not None:
                setattr(item, field.name, t)
Beispiel #6
0
def test_comparison_with_lazy():
    x = Translation(localized_string='xxx')
    lazy_u = lazy(lambda x: x, unicode)
    x == lazy_u('xxx')
    lazy_u('xxx') == x
Beispiel #7
0
 def t(s):
     return Translation(localized_string=s)
Beispiel #8
0
 def test_whitespace(self):
     t = Translation(localized_string='     khaaaaaan!    ', id=999)
     t.save()
     assert 'khaaaaaan!' == t.localized_string
def test_page_title_unicode():
    t = Translation(localized_string=u'\u30de\u30eb\u30c1\u30d712\u30eb')
    request = Mock()
    request.APP = amo.FIREFOX
    helpers.editor_page_title({'request': request}, title=t)
Beispiel #10
0
def test_comparison_with_lazy():
    lazy_u = lazy(lambda s: s, six.text_type)
    Translation(localized_string='xxx') == lazy_u('xxx')
    lazy_u('xxx') == Translation(localized_string='xxx')
Beispiel #11
0
def smorgasbord(request):
    """
    Gather many different kinds of tasty add-ons together.

    Great for testing install buttons.
    """
    def _compat(min, max):
        # Helper for faking compatible_apps.
        return {'min': {'version': min}, 'max': {'version': max}}

    addons = []
    normal_version = _compat('1.0', '10.0')
    older_version = _compat('1.0', '2.0')
    newer_version = _compat('9.0', '10.0')

    def all_versions(addon, base_tag):
        x = (('', normal_version),
             (' + older version', older_version),
             (' + newer version', newer_version))
        for extra, version in x:
            a = addon()
            a.tag = base_tag + extra
            a.compatible_apps[request.APP] = version
            addons.append(a)

    # Featured.
    featured = Addon.objects.featured(request.APP)
    addons.append(featured[0])
    addons[-1].tag = 'featured'

    normal = Addon.objects.listed(request.APP).exclude(id__in=featured)

    # Normal, Older Version, Newer Version.
    all_versions(lambda: normal[0], 'normal')

    # Unreviewed.
    exp = Addon.objects.unreviewed()
    all_versions(lambda: exp[0], 'unreviewed')

    # Multiple Platforms.
    addons.append(Addon.objects.get(id=2313))
    addons[-1].tag = 'platformer'

    # Multiple Platforms + EULA.
    addons.append(Addon.objects.get(id=2313))
    addons[-1].eula = Translation(localized_string='xxx')
    addons[-1].tag = 'platformer + eula'

    # Incompatible Platform + EULa.
    addons.append(Addon.objects.get(id=5308))
    addons[-1].eula = Translation(localized_string='xxx')
    addons[-1].tag = 'windows/linux-only + eula'

    # Incompatible Platform.
    all_versions(lambda: Addon.objects.get(id=5308), 'windows/linux-only')

    # EULA.
    eula = (Q(eula__isnull=False, eula__localized_string__isnull=False)
            & ~Q(eula__localized_string=''))
    addons.append(normal.filter(eula)[0])
    addons[-1].tag = 'eula'
    addons.append(exp.filter(eula)[0])
    addons[-1].tag = 'eula + unreviewed'

    # Contributions.
    addons.append(normal.filter(annoying=1)[0])
    addons[-1].tag = 'contrib: passive'
    addons.append(normal.filter(annoying=2)[0])
    addons[-1].tag = 'contrib: after'
    addons.append(normal.filter(annoying=3)[0])
    addons[-1].tag = 'contrib: roadblock'
    addons.append(Addon.objects.get(id=2608))
    addons[-1].tag = 'after + eula'
    addons.append(Addon.objects.get(id=8442))
    addons[-1].tag = 'roadblock + eula'

    # Other App.
    addons.append(Addon.objects.get(id=5326))
    addons[-1].tag = 'tbird'

    # Mobile.
    addons.append(Addon.objects.get(id=53476))
    addons[-1].tag = 'mobile'

    # Search Engine.
    addons.append(Addon.objects.filter(type=amo.ADDON_SEARCH)[0])
    addons[-1].tag = 'search engine'

    # Beta Version
    beta = normal.filter(versions__files__status=amo.STATUS_BETA)[0]
    beta.tag = 'beta version'

    # Theme.

    # Persona.
    addons.append(Addon.objects.filter(type=amo.ADDON_PERSONA)[0])
    addons[-1].tag = 'persona'

    # Future Version.
    # No versions.

    return render(request, 'addons/smorgasbord.html',
                  {'addons': addons, 'beta': beta})
Beispiel #12
0
 def test_whitespace(self):
     t = Translation(localized_string='     khaaaaaan!    ', id=999)
     t.save()
     eq_('khaaaaaan!', t.localized_string)