Commits

Ratnadeep Debnath  committed b63a1fc

Added system tests for SingleTranslationHandler in resource API.

  • Participants
  • Parent commits d0a1bbd

Comments (0)

Files changed (2)

File transifex/resources/api.py

         return rc.DELETED
 
 
-class SingleTranslationHandler(BaseHandler):
-    """Read and update a single translation"""
-    allowed_methods = ('GET', 'PUT')
-
-    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
-    @method_decorator(one_perm_required_or_403(
-            pr_project_private_perm,
-            (Project, 'slug__exact', 'project_slug')
-    ))
-    def read(self, request, project_slug, resource_slug,
-            language_code, source_hash, api_version=2):
-        try:
-            project = Project.objects.get(slug=project_slug)
-        except Project.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            resource = Resource.objects.get(slug=resource_slug,
-                    project=project)
-        except Resource.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            source_entity = SourceEntity.objects.get(string_hash=source_hash,
-                    resource=resource)
-        except SourceEntity.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            language = Language.objects.by_code_or_alias(language_code)
-        except Language.DoesNotExist, e:
-            return rc.NOT_FOUND
-
-        translations = TranslationModel.objects.filter(
-                source_entity=source_entity, language=language)
-
-        if not translations:
-            return rc.NOT_FOUND
-
-        field_map = {
-                'source_entity__id': 'source_entity_id',
-                'source_entity__string': 'key',
-                'source_entity__context': 'context',
-                'string': 'translation',
-                'reviewed': 'reviewed',
-                'wordcount': 'wordcount',
-                'last_update': 'last_update',
-                'user__username': 'user',
-                'source_entity__position': 'position',
-                'source_entity__occurrences': 'occurrences',
-                'source_entity__pluralized': 'pluralized'
-        }
-
-        fields = field_map.keys()
-
-        return _generate_translations_dict(
-                translations.values(*fields),
-                field_map, True)
-
-    @require_mime('json')
-    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
-    @method_decorator(one_perm_required_or_403(
-            pr_project_private_perm,
-            (Project, 'slug__exact', 'project_slug')
-    ))
-    def update(self, request, project_slug, resource_slug,
-            language_code, source_hash, api_version=2):
-        try:
-            project = Project.objects.get(slug=project_slug)
-        except Project.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            resource = Resource.objects.get(slug=resource_slug,
-                    project=project)
-        except Resource.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            source_entity = SourceEntity.objects.get(string_hash=source_hash,
-                    resource=resource)
-        except SourceEntity.DoesNotExist, e:
-            return rc.NOT_FOUND
-        try:
-            language = Language.objects.by_code_or_alias(language_code)
-        except Language.DoesNotExist, e:
-            return rc.NOT_FOUND
-
-        if language == source_entity.resource.source_language:
-            return rc.FORBIDDEN
-        data = request.data
-        user = data.get('user') and User.objects.get(username=data.get(
-            'user')) or request.user
-
-        team = Team.objects.get_or_none(project, language.code)
-        check = ProjectPermission(user)
-        if (not check.submit_translations(team or resource.project) or\
-            not resource.accept_translations) and not\
-                check.maintain(resource.project):
-            return rc.FORBIDDEN
-
-        translations = TranslationModel.objects.filter(
-                source_entity=source_entity, language=language)
-
-        if not translations:
-            return rc.NOT_FOUND
-
-        reviewed = translations[0].reviewed
-
-        update_fields = {}
-        if check.proofread(project, language):
-            if data.get('reviewed') != None:
-                update_fields['reviewed'] = data.get('reviewed')
-        else:
-            if reviewed:
-                return rc.FORBIDDEN
-
-        translation_strings = data.get('translation')
-
-        update_fields['user'] = user
-
-        if not source_entity.pluralized:
-            update_fields['string']=translation_strings
-            translations.filter(rule=5).update(**update_fields)
-        else:
-            nplurals = language.get_pluralrules_numbers()
-            for rule in translation_strings.keys():
-                if not translation_strings.get(rule, '').strip():
-                    translation_strings.pop(rule)
-            plural_forms = translation_strings.keys()
-            plural_forms.sort()
-            if nplurals != plural_forms:
-                return rc.BAD_REQUEST
-            for rule in translation_strings.keys():
-                update_fields['string'] = translation_strings[rule]
-                translations.filter(rule=rule).update(**update_fields)
-
-        field_map = {
-                'source_entity__id': 'source_entity_id',
-                'source_entity__string': 'key',
-                'source_entity__context': 'context',
-                'string': 'translation',
-                'reviewed': 'reviewed',
-                'wordcount': 'wordcount',
-                'last_update': 'last_update',
-                'user__username': 'user',
-                'source_entity__position': 'position',
-                'source_entity__occurrences': 'occurrences',
-                'source_entity__pluralized': 'pluralized'
-        }
-
-        fields = field_map.keys()
-
-        return _generate_translations_dict(
-                translations.values(*fields),
-                field_map, True)
-
 class TranslationBaseHandler(BaseHandler):
     allowed_methods = ('GET', 'PUT')
     def _generate_translations_dict(self, translations, field_map={},
             pluralized = False
             index = -1
             if translation.get('source_entity__pluralized'):
-                if buf.get(translation.get('source_entity__id')):
+                if buf.get(translation.get('source_entity__id')) != None:
                     index = buf.get(translation.get('source_entity__id'))
                     d = result[index]
                     append = False
                 result = ""
         return result
 
-
-class TranslationObjectsHandler(TranslationBaseHandler):
-    """
-    Read and update a set of translations in
-    a language for a resource.
-    """
-    allowed_methods = ('GET', 'PUT')
-
     def _get_fieldmap_and_fields(self, request):
         fields = [
                 'source_entity__id', 'source_entity__string',
 
         return (field_map_, fields)
 
+
+class SingleTranslationHandler(TranslationBaseHandler):
+    """Read and update a single translation"""
+    allowed_methods = ('GET', 'PUT')
+
+    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
+    @method_decorator(one_perm_required_or_403(
+            pr_project_private_perm,
+            (Project, 'slug__exact', 'project_slug')
+    ))
+    def read(self, request, project_slug, resource_slug,
+            language_code, source_hash, api_version=2):
+        try:
+            project = Project.objects.get(slug=project_slug)
+        except Project.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            resource = Resource.objects.get(slug=resource_slug,
+                    project=project)
+        except Resource.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            source_entity = SourceEntity.objects.get(string_hash=source_hash,
+                    resource=resource)
+        except SourceEntity.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            language = Language.objects.by_code_or_alias(language_code)
+        except Language.DoesNotExist, e:
+            return rc.NOT_FOUND
+
+        translations = TranslationModel.objects.filter(
+                source_entity=source_entity, language=language)
+
+        if not translations:
+            return rc.NOT_FOUND
+
+        field_map = {
+                'source_entity__id': 'source_entity_id',
+                'source_entity__string': 'key',
+                'source_entity__context': 'context',
+                'string': 'translation',
+                'reviewed': 'reviewed',
+                'wordcount': 'wordcount',
+                'last_update': 'last_update',
+                'user__username': 'user',
+                'source_entity__position': 'position',
+                'source_entity__occurrences': 'occurrences',
+                'source_entity__pluralized': 'pluralized'
+        }
+
+        fields = field_map.keys()
+        fields.append('rule')
+
+        return self._generate_translations_dict(
+                translations.values(*fields),
+                field_map, True)
+
+    @require_mime('json')
+    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
+    @method_decorator(one_perm_required_or_403(
+            pr_project_private_perm,
+            (Project, 'slug__exact', 'project_slug')
+    ))
+    def update(self, request, project_slug, resource_slug,
+            language_code, source_hash, api_version=2):
+        try:
+            project = Project.objects.get(slug=project_slug)
+        except Project.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            resource = Resource.objects.get(slug=resource_slug,
+                    project=project)
+        except Resource.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            source_entity = SourceEntity.objects.get(string_hash=source_hash,
+                    resource=resource)
+        except SourceEntity.DoesNotExist, e:
+            return rc.NOT_FOUND
+        try:
+            language = Language.objects.by_code_or_alias(language_code)
+        except Language.DoesNotExist, e:
+            return rc.NOT_FOUND
+
+        if language == source_entity.resource.source_language:
+            return rc.FORBIDDEN
+        data = request.data
+        user = data.get('user') and User.objects.get(username=data.get(
+            'user')) or request.user
+
+        team = Team.objects.get_or_none(project, language.code)
+        if request.user not in project.maintainers.all() and not (team\
+                and request.user in team.coordinators.all()):
+            return rc.FORBIDDEN
+
+        check = ProjectPermission(user)
+        if (not check.submit_translations(team or resource.project) or\
+            not resource.accept_translations) and not\
+                check.maintain(resource.project):
+            return rc.FORBIDDEN
+
+        translations = TranslationModel.objects.filter(
+                source_entity=source_entity, language=language)
+
+        if not translations:
+            return rc.NOT_FOUND
+
+        reviewed = translations[0].reviewed
+
+        update_fields = {}
+        if check.proofread(project, language):
+            if data.get('reviewed') != None:
+                update_fields['reviewed'] = data.get('reviewed')
+        else:
+            if reviewed:
+                return rc.FORBIDDEN
+
+        translation_strings = data.get('translation')
+
+        update_fields['user'] = user
+
+        if not source_entity.pluralized:
+            update_fields['string']=translation_strings
+            translations.filter(rule=5).update(**update_fields)
+        else:
+            nplurals = language.get_pluralrules_numbers()
+            for rule in translation_strings.keys():
+                if not translation_strings.get(rule, '').strip():
+                    translation_strings.pop(rule)
+            plural_forms = translation_strings.keys()
+            plural_forms = [int(r) for r in plural_forms]
+            plural_forms.sort()
+            if nplurals != plural_forms:
+                return rc.BAD_REQUEST
+            for rule in translation_strings.keys():
+                update_fields['string'] = translation_strings[rule]
+                translations.filter(rule=rule).update(**update_fields)
+
+        field_map = {
+                'source_entity__id': 'source_entity_id',
+                'source_entity__string': 'key',
+                'source_entity__context': 'context',
+                'string': 'translation',
+                'reviewed': 'reviewed',
+                'wordcount': 'wordcount',
+                'last_update': 'last_update',
+                'user__username': 'user',
+                'source_entity__position': 'position',
+                'source_entity__occurrences': 'occurrences',
+                'source_entity__pluralized': 'pluralized'
+        }
+
+        fields = field_map.keys()
+        fields.append('rule')
+
+        return self._generate_translations_dict(
+                translations.values(*fields),
+                field_map, True)
+
+
+class TranslationObjectsHandler(TranslationBaseHandler):
+    """
+    Read and update a set of translations in
+    a language for a resource.
+    """
+    allowed_methods = ('GET', 'PUT')
+
     @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
     @method_decorator(one_perm_required_or_403(
             pr_project_private_perm,

File transifex/resources/tests/api/__init__.py

 from transifex.resources.models import Resource, RLStats, SourceEntity
 from transifex.resources.api import ResourceHandler, TranslationObjectsHandler
 from transifex.resources.formats.registry import registry
+from transifex.resources.formats.utils.hash_tag import hash_tag
 from transifex.resources.tests.api.base import APIBaseTests
 from transifex.projects.models import Project
 from transifex.languages.models import Language
         self.assertEqual(response.status_code, 200)
 
 
-
 class SystemTestPutTranslationStrings(TransactionBaseTestCase):
     """Test updating translation strings"""
     def _setUp_test_put_translations(self):
         """Create some source strings and translations"""
-        self.entity = self.resource.entities[0]
-
-        self.source_entity1 = SourceEntity.objects.create(string='String2',
-            context='Context2', occurrences='Occurrences2',
-            resource=self.resource)
-        self.source_entity2 = SourceEntity.objects.create(string='String3',
-            context='Context3', occurrences='Occurrences3',
-            resource=self.resource)
-        self.source_entity3 = SourceEntity.objects.create(string='String4',
-            context='Context4', occurrences='Occurrences4',
-            resource=self.resource)
-        self.source_entity4 = SourceEntity.objects.create(string='String5',
-            context='context5',occurrences='Occurreneces5',
-            resource=self.resource)
-
-        # Set some custom translation data
-        # Source strings
-        self.source_string1 = self.source_entity1.translations.create(
-            string="String2",
-            language = self.language_en,
-            user=self.user['maintainer'], rule=5,
-            resource=self.resource
-        )
-
-        self.source_string2 = self.source_entity2.translations.create(
-            string="String3",
-            language = self.language_en,
-            user=self.user['maintainer'], rule=5,
-            resource=self.resource
-        )
-
-        self.source_string3 = self.source_entity3.translations.create(
-            string="String4",
-            language = self.language_en,
-            user=self.user['maintainer'], rule=5,
-            resource=self.resource
-        )
-
-        self.source_string4 = self.source_entity4.translations.create(
-            string="String with arguments: %s %d",
-            language = self.language_en,
-            user=self.user['maintainer'], rule=5,
-            resource=self.resource
-        )
-
-        self.source_string_plural1 = \
-                self.source_entity_plural.translations.create(
-            string="SourceArabicTrans1",
-            language=self.language_en,
-            user=self.user["maintainer"], rule=1,
-            resource=self.resource
-        )
-        self.source_string_plural2 = \
-                self.source_entity_plural.translations.create(
-            string="SourceArabicTrans2",
-            language=self.language_en,
-            user=self.user["maintainer"], rule=5,
-            resource=self.resource
-        )
-        # Translation strings
-        self.source_entity1.translations.create(
-            string="ArabicString2", language=self.language_ar,
-            user=self.user["maintainer"], rule=5,
-            resource=self.resource
-        )
-        self.source_entity2.translations.create(
-            string="", language=self.language_ar,
-            user=self.user["maintainer"], rule=5,
-            resource=self.resource
-        )
-
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans0", language=self.language_ar,
-            user=self.user["maintainer"], rule=0,
-            resource=self.resource
-        )
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans1", language=self.language_ar,
-            user=self.user["maintainer"], rule=1,
-            resource=self.resource
-        )
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans2", language=self.language_ar,
-            user=self.user["maintainer"], rule=2,
-            resource=self.resource
-        )
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans3", language=self.language_ar,
-            user=self.user["maintainer"], rule=3,
-            resource=self.resource
-        )
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans4", language=self.language_ar,
-            user=self.user["maintainer"], rule=4,
-            resource=self.resource
-        )
-        self.source_entity_plural.translations.create(
-            string="ArabicTrans5", language=self.language_ar,
-            user=self.user["maintainer"], rule=5,
-            resource=self.resource
-        )
+        self = create_sample_translations(self)
 
     def test_put_translations(self):
         """test updating translation strings"""
         self.assertTrue(self.source_entity1.translations.get(
             string="ArabicString2"))
 
+
+def create_sample_translations(cls):
+    self = cls
+    self.entity = self.resource.entities[0]
+
+    self.source_entity1 = SourceEntity.objects.create(string='String2',
+        context='Context2', occurrences='Occurrences2',
+        resource=self.resource)
+    self.source_entity2 = SourceEntity.objects.create(string='String3',
+        context='Context3', occurrences='Occurrences3',
+        resource=self.resource)
+    self.source_entity3 = SourceEntity.objects.create(string='String4',
+        context='Context4', occurrences='Occurrences4',
+        resource=self.resource)
+    self.source_entity4 = SourceEntity.objects.create(string='String5',
+        context='context5',occurrences='Occurreneces5',
+        resource=self.resource)
+
+    for se in SourceEntity.objects.all():
+        se.string_hash = hash_tag(se.string, se.context or '')
+        se.save()
+
+    # Set some custom translation data
+    # Source strings
+    self.source_string1 = self.source_entity1.translations.create(
+        string="String2",
+        language = self.language_en,
+        user=self.user['maintainer'], rule=5,
+        resource=self.resource
+    )
+
+    self.source_string2 = self.source_entity2.translations.create(
+        string="String3",
+        language = self.language_en,
+        user=self.user['maintainer'], rule=5,
+        resource=self.resource
+    )
+
+    self.source_string3 = self.source_entity3.translations.create(
+        string="String4",
+        language = self.language_en,
+        user=self.user['maintainer'], rule=5,
+        resource=self.resource
+    )
+
+    self.source_string4 = self.source_entity4.translations.create(
+        string="String with arguments: %s %d",
+        language = self.language_en,
+        user=self.user['maintainer'], rule=5,
+        resource=self.resource
+    )
+
+    self.source_string_plural1 = \
+            self.source_entity_plural.translations.create(
+        string="SourceArabicTrans1",
+        language=self.language_en,
+        user=self.user["maintainer"], rule=1,
+        resource=self.resource
+    )
+    self.source_string_plural2 = \
+            self.source_entity_plural.translations.create(
+        string="SourceArabicTrans2",
+        language=self.language_en,
+        user=self.user["maintainer"], rule=5,
+        resource=self.resource
+    )
+    # Translation strings
+    self.source_entity1.translations.create(
+        string="ArabicString2", language=self.language_ar,
+        user=self.user["maintainer"], rule=5,
+        resource=self.resource
+    )
+    self.source_entity2.translations.create(
+        string="", language=self.language_ar,
+        user=self.user["maintainer"], rule=5,
+        resource=self.resource
+    )
+
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans0", language=self.language_ar,
+        user=self.user["maintainer"], rule=0,
+        resource=self.resource
+    )
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans1", language=self.language_ar,
+        user=self.user["maintainer"], rule=1,
+        resource=self.resource
+    )
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans2", language=self.language_ar,
+        user=self.user["maintainer"], rule=2,
+        resource=self.resource
+    )
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans3", language=self.language_ar,
+        user=self.user["maintainer"], rule=3,
+        resource=self.resource
+    )
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans4", language=self.language_ar,
+        user=self.user["maintainer"], rule=4,
+        resource=self.resource
+    )
+    self.source_entity_plural.translations.create(
+        string="ArabicTrans5", language=self.language_ar,
+        user=self.user["maintainer"], rule=5,
+        resource=self.resource
+    )
+    return self
+
+
+class SystemTestSingleTranslationHandler(BaseTestCase):
+    def setUp(self):
+        """Create some source strings and translations"""
+        super(SystemTestSingleTranslationHandler, self).setUp()
+        self = create_sample_translations(self)
+
+    def test_single_translation_handler(self):
+        #read
+        string_hash = self.source_entity1.string_hash
+        response = self.client['team_member'].get(reverse('translation_string',
+            args=[self.project.slug, self.resource.slug, self.language_ar.code,
+                string_hash]),)
+
+        self.assertEqual(response.status_code, 200)
+        json = simplejson.loads(response.content)
+        self.assertEqual(json['translation'], self.source_entity1.translations.\
+                get(language=self.language_ar).string)
+
+        #update
+        json['translation'] = 'Hello world'
+        json['reviewed'] = True
+        response = self.client['team_member'].put(reverse('translation_string',
+            args=[self.project.slug, self.resource.slug, self.language_ar.code,
+                string_hash]),
+            data=simplejson.dumps(json),
+            content_type="application/json"
+        )
+        self.assertEqual(response.status_code, 401)
+        json['reviewed'] = True
+        response = self.client['maintainer'].put(reverse('translation_string',
+            args=[self.project.slug, self.resource.slug, self.language_ar.code,
+                string_hash]),
+            data=simplejson.dumps(json),
+            content_type="application/json"
+        )
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(simplejson.loads(response.content)['translation'],
+                'Hello world')
+
+        string_hash = self.source_entity_plural.string_hash
+        response = self.client['team_member'].get(reverse('translation_string',
+            args=[self.project.slug, self.resource.slug, self.language_ar.code,
+                string_hash]),)
+
+        self.assertEqual(response.status_code, 200)
+        json = simplejson.loads(response.content)
+        expected_translations = {}
+        for translation in self.source_entity_plural.translations.filter(
+                language=self.language_ar):
+            expected_translations[str(translation.rule)] = translation.string
+        self.assertEqual(json['translation'], expected_translations)
+
+        json['translation']['0'] = 'foo'
+        response = self.client['maintainer'].put(reverse('translation_string',
+            args=[self.project.slug, self.resource.slug, self.language_ar.code,
+                string_hash]),
+            data=simplejson.dumps(json),
+            content_type="application/json"
+        )
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(simplejson.loads(response.content)['translation'],
+                json['translation'])
+        self.assertEqual(self.source_entity_plural.translations.get(
+            rule=0).string, json['translation']['0'])